Judson Terrell Judson Terrell - 3 months ago 16
AngularJS Question

Proper way to bind to data object in Angular 2 service?

I am building an angular 2 application. The documentation has changed quite a bit since the released which has caused confusion. The best I can do is explain what I am trying to do (Which was easy in Angular 1) and hope someone can help me out.

I have created a login service using JWT's.
Once login is successful, I return a user object.

I have a loginComponent ( binds data to template ) and loginService ( which handles the https calls )

I have a userService which maintains the user object.

I have a userComponent which renders the user data.

The problem is, once the user has logged in, I am unclear on the best approach for letting the userService retrieve the new data in an object called "user", then the userComponent update its user object on the template. This was easy in angular 1 simply by putting a watcher on the userService.user object.

I tried Inputs and Outputs to no avail, eventEmitters, Observables and getters and setters. The getters and setters work, but force me to store everything in a "val()"

Can someone please tell me the best way to achieve this?


  1. User Component renders template with user.firstName, user.lastName etc.

  2. Initially user if an empty Object

  3. The login service needs to set the UserService.user

  4. The userComponent Needs to detect the change and update the DOM.



Thanks in ADVANCE!

Answer

If I'm not wrong, you are looking for a way to 'listen' to changes in your UserService.user to make appropriate updates in your UserComponent. It is fairly easy to do that with Subject (or BehaviorSubject).

-In your UserService, declare a property user with type Subject<User>.

user: Subject<User> = new Subject();

-Expose it to outside as observable:

user$: Observable<User>
...
this.user$ = this.user.asObservable();

-Login function will update the private user Subject.

login(userName: string, password: string) {
  //...
  this.user.next(new User("First name", "Last name"));
}

-In your UserComponent, subscribe to UserServive's user$ observable to update view.

this.userService.user$.subscribe((userData) => {this.user = userData;});

-In your view, simply use string interpolation:

{{user?.firstName}} {{user?.lastName}}

Here is the working plunker: http://plnkr.co/edit/qUR0spZL9hgZkBe8PHw4?p=preview

Comments