'Angular 2 service data can't assign to variable in constructor
In my Angular 2 application's constructor i need to assign service function returning data to a public variable and show in html view. Console log works well but html data not showing. So i'm assuming data is not assigning to the variable. Following is my code snippet.
export class ListComponent implements OnInit {
public listname ="Laravel list";
constructor(private laraveldataservice: LaravelDataServiceService) { }
public dataList = this.laraveldataservice.getUsers();
ngOnInit() {
this.laraveldataservice.getUsers();
}
}
Basically ng oninit data is loading in console log. But dataList value is not assigning.
Service code,
getUsers(){
const url = 'http://localhost/laravel_app/public/api/users';
this.http.get(url).subscribe(
res => {
const data = res.json();
console.log(data);
return data;
}
);
}
Solution 1:[1]
Your console.log
works because it fires in your Rx
subscription. Your dataList
never gets populated with anything due to the async
nature of the call. What I do in my code is to convert it to a promise
and then await
it.
Example:
async ngOninit() {
this.dataList = await this._httpClient
.get<TData>(url)
.toPromise();
}
Solution 2:[2]
Place it inside ngOnit and declare variable outside
public dataList : any;
ngOnInit() {
this.dataList = this.laraveldataservice.getUsers();
}
Solution 3:[3]
Try this snippet
Service
private defaultDataSub = new Subject<any>();
onDefalultDataLoad = this.defaultDataSub.asObservable();
getUsers(){
const url = 'http://localhost/laravel_app/public/api/users';
this.http.get(url).subscribe(
res => {
const data = res.json();
this.defaultDataSub.next(data);
}
);
}
Component
import {Subscription} from "rxjs";
export class ListComponent implements OnInit, OnDestroy{
public listname ="Laravel list";
constructor(private laraveldataservice: LaravelDataServiceService) { }
public dataList;
public subscription:Subscription;
ngOnInit() {
this.subscription = this.laraveldataservice.onDefalultDataLoad.subscribe(data => {
this.dataList = data;
});
}
ngOnDestroy(){
this.subscription.unsubscribe();
}
}
You are setting
dataList
property before data coming from server. May be this is the reason for your problem
Solution 4:[4]
What you need to do is :
getUsers(){
const url = 'http://localhost/laravel_app/public/api/users';
return this.http.get(url).pipe(map(res => res.json()))
}
And in your component.ts file :
export class ListComponent implements OnInit {
public listname ="Laravel list";
constructor(private laraveldataservice: LaravelDataServiceService) { }
public dataList ;
ngOnInit() {
this.laraveldataservice.getUsers().subscribe(res => {
this.dataList = res
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sajeetharan |
Solution 3 | Ashraful Islam |
Solution 4 | PiyushD |