【问题标题】:Get past request without waiting for response (Angular 2 +)无需等待响应即可获取过去的请求(Angular 2 +)
【发布时间】:2017-06-21 21:50:39
【问题描述】:

我正在通过 Get 请求在 API 中查找数据,我需要 OnInit 中的数据用于组合其他数据。问题是该方法正在被调用,但它是一个异步方法(没有等待),它到处传递,但是当获得返回时,主方法的执行已经完成,没有结果。我尝试了异步方法的实现,但没有解决。

服务:

getObjects(): MyClass[] {
let objects = new Array<MyClass>();

this.obterTodos<MyClass>(this.uriApi)
    .map(res => res.map(x => new MyClass(x.Description, x.Id)))
    .subscribe(entities => {
         objects = entities;
    });

    return objects ;
}

获取请求

public getObjects<TEntity>(url: string): Observable<TEntity[]> {
    return this.httpService
      .get(this.serviceUrl + url, this.options)
      .map(res => res.json())
      .catch(this.handleError);
}

组件:

ngOnInit() {
    this.myObjects= this.setorService.obterSetores();
    console.log('this.myObjects is empty here');
}

【问题讨论】:

    标签: json angular asynchronous get


    【解决方案1】:

    所以您需要在组件中订阅您的 observable。这通常是为了让组件可以确定何时应该运行 http 请求,并且组件可以等待 http 请求完成(并遵循一些逻辑)。

    // subscribe to observable somewhere in your component (like ngOnInit)
    this.setorService.obterSetores().subscribe(
        res => {
            this.myObjects = res;
        },
        err => {}
    )
    

    现在组件知道 http 请求何时完成

    【讨论】:

    • 这个问题是我必须在每个组件上复制代码,我想从 api 获取对象列表......对吗?
    • 这是正确的。您可以做的一件事是在最初调用 api 时存储它的结果。然后每个需要数据的后续组件都可以使用存储的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 2014-04-24
    • 2016-07-04
    • 2019-05-28
    相关资源
    最近更新 更多