Search code examples
angularrxjssubject

Subscribe to a subject only fired once


I created a service in order to get datas from an API and use a Subject to get theses datas from my component (LoadTenants is called at the app initialization):

The service :

@Injectable()
 export class TenantService{
  public tenants;
  private tenantSubject = new Subject<any>();

constructor(private http: HttpClient) {
}

LoadTenants() {
    this.http.get(TENANT_URL).subscribe((data: any) => {
        this.tenants = data;
        this.setTenants();
    });
}

setTenants() {
    this.tenantSubject.next(this.tenants);
}

getTenants(): Observable<any> {
    return this.tenantSubject.asObservable();
}

getSyncTenants() {
    return this.tenants;
}
}

The component :

public tenant;
subsciption: Subscription;

constructor(private tenantService: TenantService) { }

ngOnInit() {
        this.subsciption = this.tenantService.getTenants().subscribe((datas) => {
            this.tenant = datas;
        },
            error => console.log('Error : ', error)
        );
    }
}

ngOnDestroy() {
    this.subsciption.unsubscribe();
}

Everything is working fine on the first load, but if I navigate to an other component and come back to this one, the subscription is not fired resulting on void datas in my template.


Solution

  • If you want to get Latest Value Then Use BehaviorSubject

    BehaviorSubject will directly emit the current value to the subscriber

     @Injectable()
         export class TenantService{
          public tenants;
          private tenantSubject = new BehaviorSubject<any>();
    
        constructor(private http: HttpClient) {
        }
    
        LoadTenants() {
            this.http.get(TENANT_URL).subscribe((data: any) => {
                this.tenants = data;
                this.setTenants();
            });
        }
        setTenants() {
          this.tenantSubject.next(this.tenants);
        }
    
       getTenants(): Observable<any> {
          return this.tenantSubject.asObservable();
       }
    
       getSyncTenants() {
          return this.tenants;
       }
      }