简体   繁体   English

ngOnInit 不等待构造函数服务调用

[英]ngOnInit not waiting for constructor service call

I'm doing a API call on a constructor of a component.我正在对组件的构造函数进行 API 调用。

apiResult = [];
constructor(
        private router: Router,
        private applicationServices: ApplicationService,
        private location: Location,
    ) {
        this.applicationServices.getAppConfig().subscribe(
           result => {
              this.apiResult = result;
           }

Then on ngOnInit i want to use that information example:然后在 ngOnInit 我想使用该信息示例:

ngOnInit() {
  console.log('Selected App');
  console.log(this.apiResult );
}

However its reading the ngOnInit before the service on the constructor finish.然而,它在构造函数上的服务完成之前读取 ngOnInit。 So the result of "apiResult" is undefined.所以“apiResult”的结果是未定义的。

What options do i have and whats the best way to do this?我有什么选择,最好的方法是什么? If possible can you provide an example.如果可能的话,你能提供一个例子。

Thanks in advance.提前致谢。

While developing Angular applications, I'd suggest keeping constructors clean and just to manage dependencies.在开发 Angular 应用程序时,我建议保持构造函数的清洁并仅用于管理依赖项。

This is what I'd recommend doing:这是我建议做的事情:

export class Lol {
    apiResult = [];

    constructor(
        private router: Router,
        private applicationServices: ApplicationService,
        private location: Location,
    ) { }

    ngOnInit() {
        this.applicationServices
            .getAppConfig()
            .pipe(
                tap(result => {
                    console.log('Selected App');
                    console.log(result);
                })
            )
            .subscribe(result => {
                this.apiResult = result;
            })
    }
}

Call service in ngOnInit() and just tap result before subscribing to it, this is a rxjs operator used to do side effects and console.log is exactly that.ngOnInit()中调用服务并在订阅之前tap结果,这是一个rxjs运算符,用于做副作用, console.log就是这样。

Update更新

I'd recommend against subscribing to observables manually at all, better use async pipe to do that.我建议不要手动订阅 observables,最好使用async pipe 来做到这一点。 This way you'll avoid possible memory leaks and will let angular manage subscriptions for you.这样,您将避免可能的 memory 泄漏,并让 angular 为您管理订阅。

That'd be component file:那将是组件文件:

export class LolComponent {
  apiResult$: Observable<any[]>;

  constructor(
    private router: Router,
    private applicationServices: ApplicationService,
    private location: Location
  ) {}

  ngOnInit() {
    this.apiResult$ = this.applicationServices.getAppConfig().pipe(
      tap((result) => {
        console.log("Selected App");
        console.log(result);
      })
    );
  }
}

That'd be the template:那就是模板:

<div class="container" *ngIf="(apiResult$ | async) as apiResult">
    {{ apiResult | json }}
</div>

The actual reason is that the dependencies (parameters of your constructor) is injected and component itself is instanced.实际原因是依赖项(构造函数的参数)被注入并且组件本身被实例化。 During adding this component to the DOM, various life cycle functions execute depending on some situations.在将此组件添加到 DOM 期间,会根据某些情况执行各种生命周期函数。

Another thing is that your .getAppConfig() returns an Observable which is an asynchronous function.另一件事是您的.getAppConfig()返回一个Observable ,它是一个异步 function。 Here the function .getAppConfig() will execute in your constructor but at the same time ngOnInit() also executes.这里 function .getAppConfig()将在您的constructor中执行,但同时 ngOnInit() 也会执行。 So Obviously, the this.apiResult will be empty at that time because assigning of values to this array is not done yet.所以很明显,此时this.apiResult将为空,因为尚未完成为该数组分配值。

So, the solution could be:因此,解决方案可能是:

apiResult = [];
constructor(
        private router: Router,
        private applicationServices: ApplicationService,
        private location: Location,
    ) {   }

ngOnInit(){
 this.applicationServices.getAppConfig()
       .subscribe(result => {
              this.apiResult = result;
              consoloe.log(this.apiResult);
       });
}

Here as all suggests, keep the constructor definition clean for best practices.正如所有建议的那样,保持构造函数定义干净以获得最佳实践。

You can read about async and normal function differences.您可以阅读有关异步和正常 function 差异的信息。 Also, most importantly, Observables.此外,最重要的是,Observables。

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

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