abrahamlinkedin
abrahamlinkedin

Reputation: 467

Using services in Angular 2

I am trying to set up my Angular 2 app such that my main app.component checks whether I'm logged in and passes relevant data to a service, which is then passed onto my other components (home.component, etc).

Where I'm currently stuck is in trying to understand how to pass to and from a service variable. So I have an app.service like this:

@Injectable(){
    export class AppService {
      public logged: boolean;
    }
}

Meanwhile I have an app.component like this:

export class AppComponent {
  constructor (private appService: AppService){
  var self = this;
    firebase.auth().onAuthStateChanged(function(user){
      if (user){ self.appService.logged = true; alert("True"); }
    }); 
  }
}

By running the alert I am able to confirm that I am indeed logged in. However, I am unable to retrieve the self.appService.logged state which I have set here.

This code, for instance, does nothing.

ngOnInit(){
if (this.appService.logged){ alert("Correct"); }
}

Upvotes: 2

Views: 119

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

There is no need to use self. If you use arrow functions this. keeps pointing to the current class.

export class AppComponent {
  constructor (private appService: AppService){
    firebase.auth().onAuthStateChanged((user) => {
      if (user){ this.appService.logged = true; alert("True"); }
    }); 
  }
}

The problem in your code is, that this.appService.logged = true; is in an async callback and very probably executed after the ngOnInit() is called.

I'd suggest you make your service variable a BehaviorSubject and subscribe to that to get notfied on value changes.

https://angular.io/docs/ts/latest/cookbook/component-communication.html contains some examples.

Upvotes: 1

Related Questions