首页 > 解决方案 > app.component 文件中的订阅只能工作一次(不能工作两次)?

问题描述

我有一个父类,其中我有一个方法。在这种方法中,我有一个订阅。

代码如下所示:

 parentMethod(){
     this.token.subscribed(token=>{
     this.profile.next(token);
   });
 }

当它触发时this.profile.next(),它不会订阅app.component.ts(子类)中的配置文件。它虽然去那里一次,当应用程序加载。

app.component.ts中的代码如下所示:

 freshToken(){  //being called from constructor of app.component.ts
    this.profile.subscribe(
    (val)=>{
    console.log("Firing once");
   });
  }

我正在使用主题

谁能告诉我,为什么不是每次都开火?以及如何让它每次都着火?

标签: angularrxjs

解决方案


您可以使用服务来执行此操作:

@Injectable({
    providedIn: 'root',
})
export class YourService {

    private yourVariable: Subject<any> = new Subject<any>();


    public listenYourVariable() {
        return this.yourVariable.asObservable();

    }


    public yourVariableObserver(value ?: type) {
        this.yourVariable.next(value);
    }

您在您想要使用此服务的地方导入您的组件。

import{ YourService } from ...

在其他组件中:

submit(){
    this.yourService.yourVariableObserver();
}

在应用程序组件中

gOnInit() {
   this.sub=this.yourService.listenYourVariable().subscribe(
            variable => {
              this.callyourFunction();
            }

        )
    }

不要忘记取消订阅以防止内存泄漏

 ngOnDestroy() {
  this.sub.unsubscribe()
}

推荐阅读