Angular 2 - undefinded when sharing variable with API data between component - angularjs

Basically what i try to do is to hit my API once and save the result inside global variable in my Service, and then share and modify this value in my parent and child component with two helpers functions.
repairs.service.ts
public myItems:any[];
public GetRepairs = ():Observable<any> => {
this.headers = new Headers();
this.headers.set('Authorization', 'Bearer' + ' ' + JSON.parse(window.localStorage.getItem('token')));
return this._http.get(this.actionUrl +'repairs'{headers:this.headers})
.map((res) => {return res.json();
}).map((item) => {
let result:Array<any> = [];
if (item.items) {
item.items.forEach((item) => {
result.push(item);
});
}
this.myItems = result;
return this.myItems;
});
};
public GetItems() {
return this.myItems;
};
public UpdateItems(data:any[]) {
this.myItems = data;
};
And then in my main component i do
repairs.component.ts
export class RepairsComponent implements OnInit {
public myItems:any[];
constructor(private _userService:UserService,
private _RepairsService:RepairsService,
public _GlobalService:GlobalService) {
}
ngOnInit() {
this._userService.userAuthenticate();
this.getAllItems();
}
private getAllItems():void {
this._RepairsService
.GetRepairs()
.subscribe((data) => {
this._RepairsService.UpdateItems(data);
},
error => console.log(error),
() => {
this.myItems = this._RepairsService.GetItems();
});
}
}
This work just fine but when i try to invoke GetItems() in child component i get undefinded. I try to do it inside constructor and ngOnInit with the same result.
child.component.ts
export class ChildComponent {
private items:any[] = [];
constructor(private _RepairsService:RepairsService,
private _Configuration:Configuration) {
this.items = this._RepairsService.GetItems();
// undefinded
}
ngOnInit() {
this.items = this._RepairsService.GetItems();
// undefinded
}
}

From what i can see in the limited amount of code you shared, it would seem you are trying to get the items before the http get call finishes and saves the data. I think a better design pattern would be to make the GetItems() function also an observable or promise, and check if the data is there, if not call the http get call, and once that completes send the data back to the different components that need it.

As #MSwehli mentioned with async code execution you can't rely on the order of code lines. In this code:
ngOnInit() {
this.items = this._RepairsService.GetItems();
// undefinded
}
the async code in GetItems(); is scheduled for later execution into the event queue and then continued with the sync code. The scheduled code will be executed eventually but it's not determined when. It depends on the response of the server in this example.
If you return a Promise you can use .then(...) the chain the execution so that your code is only executed when the async execution is completed.

There are two errors/inconsistencies in your code:
userAuthenticate() call followed with getAllItems() call. These calls are async, user is not yet authenticated by the time getAllItems() is called, getAllItems will fail.
Solution here is to chain calls using rxjs flatMap:
//assuming userAuthenticate returns Observable
userService.userAuthenticate().flatMap(()=>{
return repairsService.GetRepairs();
}).subscribe(..process repairs..);
getAllItems() is called nearly at the same time as GetItems(). In most cases it fails also, because previous http request is not completed when GetItems() is called.
In my opinion early initialization is not necessary here, use service directly:
//ChildComponent
ngOnInit() {
this._RepairsService.GetRepairs().subscribe(..do anything with list of repairs i.e. assign to bindable property..);
}
You could add console.log statements in each part of the code to see the order of events in your app.

Related

Angular 5 combining and chaining parallel calls with forkJoin not working

I am looking for a way to do some action after all controls on a page are loaded. These controls are loaded in parallel by calling http get.
I tried code similar to the one below but it doesn't seem to do the trick. If it worked correctly, the sometext should display 'done'. It doesn't. I am not sure I understand correctly how the forkJoin works. I used to do this kind of chaining in Angular 1.x using promises. Any help in understanding the problem and a solution is appreciated.
The solution I am looking for is similar to this question for Angular 1.x: Angular combining parallel and chained requests with $http.then() and $q.all()
Complete code is at http://plnkr.co/edit/xH6VJo
Source is src/dash.ts
This is Angular 5 and typescript.
export class dash implements OnInit {
sometext = 'Some text ...';
private httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) {}
click_me(): void {
this.sometext = '';
forkJoin([
of(this.first_()),
of(this.second_())
]).subscribe(val => {
this.sometext = 'done...';
})
}
first_(): void {
this.http.get<any>('data/sampledata.json',this.httpOptions).subscribe(val=> {
this.sometext = val.items[0].value;
});
}
second_(): void {
this.http.get<item[]>('data/sampledata.json',this.httpOptions).subscribe(val=> {
this.sometext = val.items[1].value;
});
}
}
The main reason is because your first() and second() doesn't return an Observable. .forkJoin() can only take in an array of Observables, fire them in parallel, and then it has to wait for all observables to complete before it starts to emit the resultant values. The main reason your complete() handler never gets executed is because there is no Observables in the .forkJoin() in the first place, hence none of them can complete, and your .forkJoin() will never emit.
Here's what you should do. For first() and second(), have them return an observable. If you want to change the this.sometext when both of them executes, use the operator .do():
first_(): Observable<any> {
this.http.get<any>('data/sampledata.json', this.httpOptions)
.do(val => {
this.sometext = val.items[0].value;
});
}
second_(): Observable<any> {
this.http.get<item[]>('data/sampledata.json', this.httpOptions)
.do(val => {
this.sometext = val.items[1].value;
});
}
Now your click_me() should be working fine:
click_me(): void {
this.sometext = '';
forkJoin([
of(this.first_()),
of(this.second_())
]).subscribe(val => {
this.sometext = 'done...';
})
}
Note that since Observable.forkJoin() fires their requests in parallel, there is NO GUARANTEE that your first() will be executed before your second().

Calling observable function in same class in angular2

I have two function in a class where
First function returns Observable.
Second function is called from other component
I want call first function in second use the value of first and process it.
Sample code:
#Injectable()
export class SampleService {
service:string;
getService(): Observable<any> {
return this._http.get(`url`, {
headers: this.headers()
}).map(res=>res.json();)
.catch(err=>console.log(err);
}
}
generateToken():string{
const service="";
this.getService().subscribe(res=>{service=res});
//process it
return service;
}
Whenever i call the second function the value of service is return as empty.How to await till the subscribe is over and then process.
You can't return a value that you get from an observable.
You can either use map in the 2nd method as in the first method and then subscribe where you call generateToken
generateToken():string{
return this.getService().map(res=>{return service=res});
}
someMethod() {
this.generateToken.subscribe(res => this.service = res);
}
or assign it to a field in the 2nd property
generateToken():string{
return this.getService().subscribe(res=>{this.service =res});
}
update
someMethod() {
this.generateToken.subscribe(res => {
this.service = res;
// other code here
});
}
This will return asynchronously because the subscribe will not come back until it receives a response:
generateToken():string{
const service="";
this.getService().subscribe(res=>{service=res}); //Async
return service; //Instant return of blank value
}
I would suggest returning the observable itself and subscribing to it where you need it:
generateToken(){
return this.getService().map(res => res.json()); //presuming json payload
}
Then inside your components after requesting sampleService in constructor:
this.sampleService.generateToken().subscribe(data = > { //use data });

Nativescript Angular ActivityIndicator

in my Nativescript Angular app i am using an ActivityIndicator, setup as i've seen in the Nativescript Angular docs (the GroceryList example):
<ActivityIndicator width="30" height="30" [busy]="refreshing" [visibility]="refreshing ? 'visible' : 'collapsed'" horizontalAlignment="center" verticalAlignment="center"></ActivityIndicator>
if the Component using it i have:
export class MyComponent {
public refreshing = false;
........
}
Then i fetch some data from my backend:
public onRefreshTap() {
console.log("onrefreshtap");
this.refreshing = true;
this.backend.getData(function (data) { //this.backend is my Service
this.refreshing = false;
})
}
The problem is that when i put this.refreshing to true, the ActivityIndicator correctly shows. But when bakend request completes (and so, i put this.refreshing=false) the ActivityIndicator does not hides... (and also it seems that its busy property is not updated, it stays in spinning state)..
What am i doing wrong ?
Thanks in advance
You could also try to access the refreshing property as it has been shown in the sample codes below. It could be a problem of accessing the property inside the callback method of your service.
public onRefreshTap() {
var that = this;
this.refreshing = true;
this.backend.getData(function (data) { //this.backend is my Service
that.refreshing = false;
})
}
or
public onRefreshTap() {
this.refreshing = true;
this.backend.getData((data) => {
that.refreshing = false;
})
}
It may be many things:
1) The change to false, on the Observable, is not being "seen" by the component.
------ The solution is run the code in a Zone (see https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html )
2) The backend is returning an error (I don't see it dealing with that in the code).
------ The solution is put a function to deal with the error.
3) The callback is not being called. In your code, you're SENDING a function as a parameter to the backendService, so maybe the service is not executing it.
------ Try using a Promisses or Observables to deal with returned values (you'll have to Google about it, since I'm still learning them my explanation would be the worst). :)
Here's some code that might work:
my-component.html
<ActivityIndicator [busy]="isWorking" [visibility]="isWorking?'visible':'collapse'"></ActivityIndicator>
my-component.ts
import { Component, NgZone } from "#angular/core";
...
export class MyComponent {
isWorking:boolean = false;
constructor(private backendService: BackendService,
private _ngZone: NgZone)
{
this.isWorking = false;
}
public onRefreshTap() {
console.log("onrefreshtap");
this.isWorking = true;
this.backendService.getData()
.then(
// data is what your BackendService returned after some seconds
(data) => {
this._ngZone.run(
() => {
this.isWorking = false;
// I use to return null when some Server Error occured, but there are smarter ways to deal with that
if (!data || data == null || typeof(data)!=='undefined') return;
// here you deal with your data
}
)
}
);
}
}

Angular 2 TS object array only defined while subscribed to service

I'm in the process of learning Angular 2 using TypeScript. So far I've written a little API service that uses HTTP get method to feed me json data using observables. Everything is working fine, I can use the data in my view, I can also use the data in my component, but only while I'm subscribed to the getData() method.
Why is that and what other possibilities do I have to make the object array available to all methods in my component for easy iteration and management?
Example component:
export class SomeComponent implements OnInit {
public someData: DataObject[];
public constructor(private service: SomeService) {}
public ngOnInit(): void {
this.loadData();
this.useData();
}
private loadData(): void {
this.service.getData().subscribe(data=> {
this.someData = data;
this.someData.forEach(dataObject => {
// this works fine
});
});
}
private useData(): void {
this.someData.forEach(dataObject => {
// dataObject is (of type?) undefined, why?
});
}
}
It's because http calls are async. Your this.useData(); does not wait this.loadData(); to finish. This should work:
private loadData(): void {
this.service.getData().subscribe(data=> {
this.someData = data;
this.useData();
});
}

Angular2 RxJS calling class function from map function

I'm new to Angular 2 and Observables so I apologise if my problem is trivial. Anyway I'm trying to test the Angular 2 HTTP Client using RxJS. Although I got it to work I need to add more logic to the service I'm currently working on. Basically I'd like to have a mapping function to convert the object I receive from the web service I'm connected to, to the model object I have in Angular.
This is the code that works:
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
import { Person } from '../models/person';
#Injectable()
export class PersonsService {
constructor(private http: Http) { }
private personsUrl = 'http://localhost/api/persons';
getPersons(): Observable<Person[]> {
return this.http.get(this.personsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
if(res.status < 200 || res.status >= 300) {
throw new Error('Bad response status ' + res.status);
}
let body = res.json();
return body.data || {};
}
private handleError(error: any) {
let errMsg = error.message;
return Observable.throw(errMsg);
}
}
With the above code I have no problems whatsoever. The issue I'm having is that I'd like to map the object I'm getting from the service to the one I have in Angular i.e. Person. What I tried is to call another function from the extractData function that's being used by the .map function.
private extractData(res: Response) {
if(res.status < 200 || res.status >= 300) {
throw new Error('Bad response status ' + res.status);
}
let body = res.json();
// map data function
var data = this.mapData(body.data);
return data || {};
}
private mapData(data: any) {
// code to map data
}
Obviously the code above doesn't work as when this is referenced inside the extractData function, this does not refer to the PersonsService class, but it refers to a MapSubscriber object.
I don't know if it is possible to call an "external" function. It might be a silly thing but I can't find any information regarding this.
Instead of just passing the function reference use arrow functions to retain this
.map((res) => this.extractData(res))
Observable's map function allows you to pass a reference variable as a second argument on how should this actually work inside the higher-order function.
so the solution is
.map(this.extractData,this)
This way while passing the extractData function you are also passing the current class's this execution context to the higher-order function.
It will work.
Observable Doc Reference Link

Resources