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

时间:2018-05-25 11:54:45

标签: angular typescript angular6

我有一个组件,其上有一个微调器,它放在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中的服务,除非有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

在您的服务中使用主题 BehaviorSubject ,并在您的组件中使用订阅方法获取最新值。

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

答案 1 :(得分:1)

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

   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);
      });
   }
相关问题