Angular 6 - 控制组件是否从服务或其他组件可见

Angular 6 - Control if component is visable or not from service or other components

我有一个组件,上面有一个微调器,它位于 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 上并且有一个变量显示和隐藏它...如何从其他组件或服务更改该值那是住在 app.component.ts,除非有更好的方法吗?

在您的服务中使用 SubjectBehaviorSubject 并在您的组件中使用相同的订阅方法来获取最新值。

service.ts 文件

isLoading = true;
public loader = new BehaviorSubject(isLoading)

getData(){
 this.http.get(this.url).subscribe(()=>{
  this.isLoading = false
  this.loader.next(this.isLoading)
})

.component.ts

ngOnInit(){
 this.testService.loader.subscribe(value=>console.log(value))
}

在您的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);
      });
   }