简体   繁体   中英

Wait for function to finish in angular4

I have a part of code that doesn't work like I want it.

challengeService.getChallenge(1,this.navParams.get("val1",val2))
    .map(res => res.json())
    .catch(err =>  {

      alert('UI error handling');
      alert(err);
      return Observable.throw(err); // observable needs to be returned or exception raised
    })
    .subscribe((data) => {
      this.challenge = ((data[0]));
    });
return this.challenge;

It talks to my challengeservice, code here:

getChallenge(val1, val2)
{
    this.storage.ready().then(() => {
        this.storage.get('jwt').then((val) => {

            let authHeader = new Headers();

            authHeader.append('x-access-token', val);

            this.challenges =  this.http.get('http://localhost:8080/api/val3/'+val1+'/'+val2+'', {
                headers: authHeader
            });
        });
    });
    return this.challenges;
}

In the first part of my code, I now get an map error (cannot .map on undefined) because my challenges array is obviously empty. When I put my return statement in the storage brackets, the program nags about not return an array, but returning nothing (void). How do i make my challengepage wait for my challengeservice to get data from the api and fill the data correctly?

Thanks in advanced!

Consider changing the order and organization of the http call to more closely follow with common practice.

If you are not using the new HttpClient, then the service code normally looks something like this:

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

Notice that this is where the mapping of the response occurs. (I know you need some other code here regarding your storage checks ... but this shows how the map is often used.)

The component code then looks something like this:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}

This is where the subscribe is handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM