2017-06-21 61 views
0

我正在通过Get请求查找API中的数据,我需要我的OnInit中的数据用于撰写其他数据。问题在于该方法正在被调用,但它是一个异步方法(无需等待),它在任何地方通过,但是当获得返回时,主方法的执行已经完成,没有结果。我尝试了异步方法的实现,但没有解决。获取过去的请求而无需等待回复(Angular 2 +)

服务:

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 ; 
} 

GET请求

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'); 
} 

回答

1

所以你要订阅组件中的可观察值。通常这样做是为了让组件可以确定何时应该运行http请求&,以便组件可以等待http请求完成(并遵循一些逻辑)。

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

现在组件知道当HTTP请求完成

+0

这样做的问题是,我将不得不复制我想从一个API的对象是列表中的每个组件的代码是...那对吗? –

+1

这是正确的。您可以做的一件事就是在最初调用api时存储api的结果。那么每个需要数据的后续组件都可以使用存储的数据 – LLai