How to display an [object Object] on angular UI? - node.js

I am trying to display the response of my backend api http://localhost:3000/api/radar_life_cycle on the angular UI but somehow I get the output as [object Object] ,console.log on the response shows the correct object but not on the UI,what am I missing?any guidance on how to display the object on UI?
html
<textarea rows="6" [(ngModel)]="enteredValue"></textarea>
<hr>
<button (click)="get_radar_lifecycle_data()">Search</button>
<p>{{newPost}}</p>
component.ts
import { Component, OnInit, Injectable } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { Subject } from "rxjs";
import { map } from 'rxjs/operators';
#Component({
selector: 'app-radar-input',
templateUrl: './radar-input.component.html',
styleUrls: ['./radar-input.component.css']
})
export class RadarInputComponent {
constructor(private http: HttpClient) {}
newPost = '';
get_radar_lifecycle_data(){
this.http.get('http://localhost:3000/api/radar_life_cycle',{params:this.enteredValue}).subscribe(response => {
console.log(response);
this.newPost = response
});
}
}
response:-
{message: "Posts fetched successfully!", posts: Array(1)}
CURRENT OUTPUT:-

You need inspect your object structure by json pipe
Display your object property by ngFor because result return Array.
https://stackblitz.com/edit/angular-d17ggk

You can use the built-in JSON pipe that Angular has which is included in #angular/common and is imported with BrowserModule or CommonModule:
<textarea rows="6" [(ngModel)]="enteredValue"></textarea>
<hr>
<button (click)="get_radar_lifecycle_data()">Search</button>
<p>{{newPost | json}}</p>
For more info about the pipe, check out the JsonPipe API.

By referring {message: "Posts fetched successfully!", posts: Array(1)}!
You can use *ngFor to display the Array like:
<div *ngFor="let item of newPost?.posts">
{{ item.milestone }}
</div>
or to display properties:
{{ newPost?.message }}
Edit:
Change:
newPost = '';
to:
newPost: any;
and you already have access of object of that array so you just need to do:
{{ item.milestone }}
Working Demo

Related

Why can React display an object but not its members?

I'm trying to wrap my head around the MERN stack. So far I've managed to query my database and get the data on an API endopoint, but I'm having some trouble getting it to show up on my front-end.
Here's my fronted code :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component<{}, {res:any}> {
constructor(props:any) {
super(props);
this.state = {res: Array};
}
callAPI() {
fetch("http://localhost:5000")
.then(res => res.json())
.then(json => this.setState({res: json}));
}
componentWillMount() {
this.callAPI();
}
render() {
// WORKS
console.log(this.state.res[0]);
// DOESN'T WORK
console.log(this.state.res[0].name);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
)};
}
export default App;
As you can see it's just a modified version of the default React homepage. I just added a state and fetching data from my backend.
The problem comes when I try to console.log my data.
If I console.log(this.state.res[0]), everything is fine, and I get { "_id": "62207b47d40bca8ea8b60560", "name": "Patère", "checked": false, "links": [ "" ] } in my console. But if I try to only log the name, I get Uncaught TypeError: this.state.res[0] is undefined, which is weird, since it managed to display this.state.res[0] just fine before ?
What's causing this and how can I fix it ?
Thank you in advance.

Angular 7 ngx-translate change run time transaltion without refresh page

Notes: I tired all questions & answers related to this topic.
I want to Translate Typescript variable Value without refresh page on change language Dropdown .
I trying To change the language-wise data change. I success to change to HTML Bind: value on dropdown value change but not update TypeScript Bind: value.
i use ngx-translate
I referer Links: but not success
angular-ngx-translate-usage-in-typescript
ngx-translate-in-ts-file-angular
ngx-translate-with-dynamic-text-on-ts-file
components.ts
import { Component, OnInit } from '#angular/core';
import { TranslateService } from '#ngx-translate/core';
#Component({
selector: 'app-translate',
templateUrl: './translate.component.html',
styleUrls: ['./translate.component.css']
})
export class TranslateComponent implements OnInit {
typeScriptvalue: string;
simpleProducts:any[]=[ {
name:'English',
id:'en'
},
{
name:'French',
id:'fr'
}];
constructor(private translate: TranslateService) {
this.typeScriptvalue = this.translate.instant('HOME.TITLE');
}
ngOnInit(): void {
}
changeevent(e)
{
console.log(e);
this.translate.use(e.value);
}
}
component.html
<label><b> HTML Bind</b></label> : <div>{{ 'HOME.TITLE' | translate }}</div> <br>
<label><b>TypeScript Bind</b></label> : <div>{{ typeScriptvalue }}</div> <br>
<label>
Change language : <div class="dx-field-value">
<dx-select-box [dataSource]="simpleProducts" displayExpr="name" valueExpr="id" (onValueChanged)="changeevent($event)"></dx-select-box>
</div>
</label>
After long research I have finally got the best solution.
You can reassign the Typescript variable on the subscriber method. use method
changeevent(e)
{
console.log(e);
this.translate.use(e.value).subscribe(data => {
this.typeScriptvalue = this.translate.instant('Home.Title');
});
}

How to display images in Bootstrap carousel using React

So I have a component(Posts) in which a loop through all the posts from the Database. In the component, I 'embedded' another component(PostItem) so I dont have to create a different component for viewing individual entries. Now inside the PostItem component I have another component with the name of 'PostGallery'.
This is the current code that I have in PostItem.js file:
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import PostGallery from '../posts/PostGallery';
const PostItem = ({
post: { _id, text, name, files, avatar, user, likes, comments, date },
}) => (
<article className={_id}>
<Link to={`/posts/${_id}`}>
<div id="carouselExampleIndicators" className="carousel slide" data-ride="carousel">
<div className="carousel-inner">
{files.slice(0, 5).map((file, index) => (
<PostGallery key={index} post={file} />
))}
</div>
</div>
</Link>
</article>
);
PostItem.propTypes = {
post: PropTypes.object.isRequired,
};
export default connect(
null, null
)(PostItem);
When posting an entry the user can post URL from images separated by comma which is working just fine. The problem comes when displaying it in the front-end.
This is what I have in my PostGallery component:
import React from 'react';
import PropTypes from 'prop-types';
const PostGallery = ({
post: { files }
}) => {
return (
<div className="">
{post.files.length > 0 ? (
post.files.map(file => (
<img key={file} src={file} alt="" />
))) : (
<p>No images found</p>
)
}
</div>
);
};
PostGallery.propTypes = {
post: PropTypes.object.isRequired,
};
export default PostGallery;
I believe this should be easy but somehow its just now working and the console it's not trowing me any errors related to it. So if you guys can help...
Thanks!

Where to find current user info inside the user JSON object?

I am trying to find out how to get certain data belonging to the current logged-in user such as full name, email, etc.
The Firefox console outputs this:
----- header.component.ts -----
this.user:
{}
authService.getUser()
Object { _isScalar: false, source: {…} }
this.authService.me()
Object { _isScalar: false, _subscribe: me() }
-------------------------------
This prints out what the authService can provide using console.log() (see the TypeScript code below).
I look through the Object returned by the authService.getUser() method and also the one returned by the this.authService.me() method, but I cannot manage to find where any of the info is located.
I noticed in the HTML code (in a part that was made by the Mean.io generator and not by me) that it references "user.fullname" to display the user's full name in the header bar, but how? And how would you access other pieces of information such as the user's email, phone number, etc?
My profile component TypeScript file looks like this:
import { Component, OnInit, Input } from '#angular/core';
import { Router } from '#angular/router';
import { AuthService } from '../auth/auth.service';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
#Input() user: any = {};
constructor(
private authService: AuthService,
private router: Router
) { }
ngOnInit() {
console.log("----- header.component.ts -----");
console.log("this.user:");
console.log(this.user);
console.log("-------------------------------");
}
profile(): void {
this.navigate('/profile');
}
logout(): void {
this.authService.signOut();
this.navigate('/auth/login');
}
navigate(link): void {
this.router.navigate([link]);
}
}
And my profile component HTML file looks like this:
<header >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=ZCOOL+XiaoWei" rel="stylesheet">
<mat-toolbar color="primary">
<a [routerLink]="['/']" class="logo"></a>
<a [routerLink]="['/']" class="toolbar-buttons"> Home </a>
<a class="toolbar-buttons"> Deals </a>
<a [routerLink]="['/about']" class="toolbar-buttons"> About </a>
<span class="example-spacer"></span>
<a class="links side" [routerLink]="['/auth/login']" *ngIf="!user">Login</a>
<div>
<a class="links side" *ngIf="user" [matMenuTriggerFor]="menu">
<mat-icon>account_circle</mat-icon>{{user.fullname}}
</a>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngIf="user && user.isAdmin" [routerLink]="['/admin']">admin</button>
<button mat-menu-item (click)="logout()">logout</button>
<button mat-menu-item (click)="profile()">profile</button>
</mat-menu>
</div>
</mat-toolbar>
</header>
It turns out the user is not settled instantly, It waits for some ajax response, You could use ngOnChanges event and then access the user object like this
ngOnChanges(){
if(this.user && this.user.fullname){
//Do your work here
}
}

can get data out of http request

i have a problem receiving data to variable.
this works:
this.http.get(some_url).subscribe(
data => {
console.log(JSON.parse(data['_body']))
});
but if i try to get the value to a variable instead of printing it, it does not work:
this.http.get(some_url).subscribe(
data => {
this.var = JSON.parse(data['_body'])
});
i need your help, i tried everything.
Thanks!
This doesn't seem to be an angular 2 issue. Can you try the following steps to debug?
Check the console (F12) for any errors while making the GET call
Print and store the returned the data in the variable
Are there any lines above the variable assignment line that you have not posted?
I've created a plunker where you can see the variable assignment in action
https://embed.plnkr.co/MEHTZ92HgZhEbUZlBELQ/
the app.component.ts is as follows
import { Component } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'my-app',
template: `
<div>
<p>Content: {{ content }}</p>
</div>
`,
})
export class AppComponent {
content: string;
constructor(private http: Http) {
this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe(
data => {
this.content = data
});
}
}
And the result I get is
Content: Response with status: 200 OK for URL: https://jsonplaceholder.typicode.com/posts/1
Of course, one shouldn't use the constructor for network calls and similar heavy stuff and should use ngOnInit instead, but just for the sake of example I've made the call in the constructor

Resources