首页 > 解决方案 > Angular 6 - 控制组件是否可以从服务或其他组件中看到

问题描述

我有一个组件,上面有一个微调器,它放在 app.component.html

<app-spinner *ngIf="isLoading"></app-spinner>

在我的 app.component.ts 上,我将 isLoading 设置为 False 开始。

然后我有一个服务,其中包含 getData 之类的方法。

getData() {
    // show spinner
    this.http.get('url here');
    // Hide Spinner
}

我的问题是...如果微调器位于 app.component.html 和 .ts 上,并且那里有一个显示和隐藏它的变量...如何从其他组件或应用程序中的服务更改该值。 component.ts,除非有更好的方法来做到这一点?

标签: angulartypescriptangular6

解决方案


在你的 app.component.ts 中订阅服务方法,并在订阅服务的 getData() 方法的响应时设置 isLoading 布尔

   getDataFromService() {
    // show spinner whilst waiting for the request
    this.isLoading = true;
    this.yourServiceName.getData()
      .subscribe(res => {
        // Hide spinner when res is received
        this.isLoading = false;
        // do something with the repsonse
        console.log(res);
      });
   }

推荐阅读