简体   繁体   English

Angular2,使用主要组件的onInit调用服务

[英]Angular2, Using the main component's onInit to call services

I was wondering how exactly works the onInit, especially when calling some services. 我想知道onInit的工作原理,特别是在调用某些服务时。 Here is my main component : 这是我的主要组成部分:

@Component({
    selector: "app",
    templateUrl: "app/app.html",
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig(){
...
}
export class AppComponent implements OnInit {
    constructor (private _fooManager: FooManager) {}

    ngOnInit() {
        this._fooManager.fetchAllFoos() // Do a web service call to fetch some data and store them inside the FooManager
    }
}

( FooManager 's injection comes from my bootstrap.ts) FooManager的注入来自我的bootstrap.ts)

then all my other components are using the FooManager's data (especially in their templates). 那么我所有其他组件都在使用FooManager的数据(尤其是在其模板中)。 I was wondering if I had to check the status of the call done in the fetchAllFoos or if the ngOnInit gives any guarantees that the values are fully loaded ? 我想知道是否必须检查在fetchAllFoos完成的调用的状态,或者ngOnInit是否可以保证值已完全加载?

If not, I guess one solution would be to give a promise back and then check the promise status. 如果没有,我想一种解决方案是将诺言放回,然后检查诺言状态。

ngOnInit() doesn't do anything special except being called at some point after the component was initialized. ngOnInit()除了在组件初始化之后的某个时刻被调用之外,没有做任何特殊的事情。

What you want is probably something like What is the correct way to share the result of an Angular 2 Http network call in RxJs 5? 您想要的可能类似于: 在RxJs 5中共享Angular 2 Http网络调用结果的正确方法是什么?

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

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