I have a service in my angular application, like this, to preserve user status:
public activeUser = new BehaviorSubject(null);
I do the following:
Go to component A and in the constructor I signed up for this question (auth is the service that was imported):
this.auth.activeUser.subscribe((status) => { console.log("subscribe >>>", status); this.isAuth = status; });
In another method of these components, I do this:
this.auth.activeUser.next(true);
if the user is successfully registered, and set to false if there are some problems.
Greate, it works, I have console output.
But I have another component that should use activeUser status. In this component, I imported the service and perform the following actions:
ngOnInit() { this.auth.activeUser.subscribe( (userStatus:boolean) => { this.isAuth = userStatus; console.log("this is foo HomeComponent", this.isAuth); } ); console.log("home activeUser", this.auth.activeUser); }
I believe that when in the first component, Subject gets next(true) or next(false) , I should see this is foo HomeComponent in the console, but it is not.
I found this answer. Subscription method does not respond to changes [Angular 2]
and accordingly, I did the following:
- Go to app.module.ts
- Imported Service
- Add service to providers []
Hmmm, I was hoping my problem would be resolved. But no. I went back to my second component and removed the import using the service. But now I can not compile the code:
this.auth.activeUser.subscribe
where auth is the service introduced. I even restarted webpack, but still fails. Thank you for your help.
There is a complete second component:
import {Component, OnInit} from '@angular/core'; import {AuthService} from "../../platform/auth.service"; import {Observable} from "rxjs"; @Component({ selector: 'home-page', templateUrl: 'home.component.html', styleUrls:['home.component.scss'] }) export class HomeComponent implements OnInit { public isAuth: boolean; constructor(private auth: AuthService) { this.isAuth = true; } ngOnInit() { this.auth.activeUser.subscribe( (userStatus:boolean) => { this.isAuth = userStatus; console.log("this is foo HomeComponent", this.isAuth); } ); console.log("home activeUser", this.auth.activeUser); } }
My app.module.ts
import {AuthService} from "./platform/auth.service"; @NgModule({ imports: [ BrowserModule, // CommonModule, ReactiveFormsModule, routing, ModalModule, NgbModule, HttpModule ], declarations: [ AppComponent, HomeComponent ], providers: [ appRoutingProviders, AuthService ], bootstrap: [ AppComponent] }) export class AppModule { }
My service:
@Injectable() export class AuthService { public activeUser = new BehaviorSubject(null); constructor(private http: Http, private interaction:InteractionService) { } }