简体   繁体   English

等待功能在angular4中完成

[英]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: 它与我的challengeservice对话,代码如下:

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. 在我的代码的第一部分中,我现在遇到一个映射错误(无法对未定义的.map进行映射),因为我的Challenge数组显然为空。 When I put my return statement in the storage brackets, the program nags about not return an array, but returning nothing (void). 当我将return语句放在存储括号中时,该程序na绕不返回数组,而是不返回任何内容(无效)。 How do i make my challengepage wait for my challengeservice to get data from the api and fill the data correctly? 如何使我的Challengepage等待我的ChallengeService从api获取数据并正确填充数据?

Thanks in advanced! 提前致谢!

Consider changing the order and organization of the http call to more closely follow with common practice. 考虑更改http调用的顺序和组织,以更紧密地遵循常规做法。

If you are not using the new HttpClient, then the service code normally looks something like this: 如果您不使用新的HttpClient,则服务代码通常如下所示:

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. 这是处理订阅的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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