0

I have an AuthService, that contains actual user data and method for login. If I click on 'Login button', I call my AuthService to get new user data from server and rewrite 'this.user' value;

So, in a header, I show the username.

Question: How my HeaderComponent can know, that this.user in the AuthService is changed ?

Dmytro Vlasenko
  • 11
  • 1
  • 1
  • 1

1 Answers1

3

Well, you can expose an Observable on your AuthService. Then you will be able to subscribe to this stream in your HeaderComponent. You can use the EventEmitter class which extends the RxJS Subject class. Moreover, you can use a TypeScript setter to automatically trigger the event for changes. So, your code should look like :

@Injectable()
export class AuthService {
    private _user: any;
    userStream: EventEmitter<any>;


    constructor() {
      this.userStream = new EventEmitter();
    }

    //code ...

    getUserData() {
      //call our setter
      this.user = newData;
    }

    set user(newValue) {
      this._user = newValue;
      //set user data and emit a value in the userStream
      this.userStream.emit(newValue);
    }
}

Then you can use your service in your component :

@Component({...})
export class HeaderComponent {
    currentUser: any;

    constructor(private authService: AuthService) {
        //subscribe to the stream to be notified when user data has changed
        authService.userStream.subscribe((newUser) => { this.currentUser = newUser; });
    }
}

So you will be able to listen change on your user data.

Paul Boutes
  • 3,285
  • 2
  • 19
  • 22
  • 2
    FYI, [this answer](http://stackoverflow.com/a/36076701/6680611) suggests that an Angular 2 `EventEmitter` should not be used in that manner. You could just use an RxJS `Subject` instead. – cartant Oct 03 '16 at 04:32