Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 615
Judson Terrell Avatar asked Aug 13 '16 02:08

Judson Terrell


People also ask

What is one-way data binding and two-way data binding in Angular?

Difference between One-way & Two-way Binding This means that the flow of code is from ts file to Html file as well as from Html file to ts file. In order to achieve one-way binding, we used the property binding concept in Angular. In order to achieve a two-way binding, we will use ngModel or banana in a box syntax.

Which Angular module helps you achieve two-way data binding?

Two-way data binding can be achieved using a ngModel directive in Angular. The below syntax shows the data binding using (ngModel), which is basically the combination of both the square brackets of property binding and parentheses of the event binding.

Why data binding is not working Angular?

You have main issue is that you have used ngModel for select element. So when you select item from select element at that time value is changed in selectedIds[rowIndex] item. I have applied minor code refactoring in first div as per below it will helpful to you.

What is data binding in Angular with example?

Two-way data binding is a two-way interaction, data flows in both ways (from component to views and views to component). Simple example is ngModel. If you do any changes in your property (or model) then, it reflects in your view and vice versa. It is the combination of property and event binding.


2 Answers

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

like image 198
Harry Ninh Avatar answered Oct 13 '22 01:10

Harry Ninh


There are two rather different approaches you could take:

1. Share data via JavaScript reference types

If you create an object in your UserService

@Injectable()
export class UserService {
   public user = new User();

you can then share that object just by virtue of it being a JavaScript reference type. Any other service or component that injects the UserService will have access to that user object. As long as you only modify the original object (i.e., you don't assign a new object) in your service,

   updateUser(user:User) {
       this.user.firstName = user.firstName;
       this.user.lastName  = user.lastName;
   }

all of your views will automatically update and show the new data after it is changed (because of the way Angular change detection works). There is no need for any Angular 1-like watchers.

Here's an example plunker.

In the plunker, instead of a shared user object, it has a shared data object. There is a change data button that you can click that will call a changeData() method on the service. You can see that the AppComponent's view automatically updates when the service changes its data property. You don't have to write any code to make this work -- no getter, setter, Input, Output/EventEmitter, or Observable is required.

The view update automatically happens because (by default) Angular change detection checks all of the template bindings (like {{data.prop1}}) each time a monkey-patched asynchronous event fires (such as a button click).

2. "Push" data using RxJS

@HarryNinh covered this pretty well in his answer. See also Cookbook topic Parent and children communicate via a service. It shows how to use a Subject to facilitate communications "within a family".

I would suggest using a BehaviorSubject instead of a Subject because a BehaviorSubject has the notion of "the current value", which is likely applicable here. Consider, if you use routing and (based on some user action) you move to a new route and create a new component, you might want that new component to be able check the "current value" of the user. You'll need a BehaviorSubject to make that work. If you use a regular Subject, the new component will have no way to retrieve the current value, since subscribers to a Subject can only get newly emitted values.


So, should we use approach 1. or 2.? As usual, "it depends". Approach 1. is a lot less code, and you don't need to understand RxJS (but you do need to understand JavaScript reference types). Approach 2. is all the rage these days.

Approach 2. could also be more efficient than 1., but because Angular's default change detection strategy is to "check all components", you would need to use the OnPush change detection strategy and markForCheck() (I'm not going to get into how to use those here) to make it more efficient than approach 1.

like image 30
Mark Rajcok Avatar answered Oct 13 '22 00:10

Mark Rajcok