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

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?
User Component renders template with user.firstName, user.lastName etc.
Initially user if an empty Object
The login service needs to set the UserService.user
The userComponent Needs to detect the change and update the DOM.
Thanks in ADVANCE!

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

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.

Related

Angular 2: Creating a global, settable, observable property?

I've got an Angular 2 app (using v2.1.0) with an authentication service to allow the user to login and logout of the app. I want to create a globally available boolean property that can be set when a user logs in or logs out so I can easily show and hide parts of the UI based on the state of the user. Something like isAuthenticated would be fine. However, I'm not entirely sure what the best method is to create a global class/service, or what the recommended method is. I found this question, which does address it, but all of the answers are from way before the final release came out, and I believe are outdated. Currently I have a property on every component where I need to keep track of the logged in state that goes back to the authentication service, but it seems inefficient to me:
IsAuthenticated: boolean = this.authService.isAuthenticated();
You can try use *ngIf to add or remove element | Visibility to hide or show element
<div *ngIf="IsAuthenticated">Content</div> //add or remove
<div [class.hidden]="!IsAuthenticated">Show with class</div> //show or hide
For more detail
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngIf
Add a boolean property to your service and default it to false. When the user logs in set it to true. Create a function in your service to return the boolean. Then just call it like you call your login function.
Services are singletons and do just what you are asking for.
First you need to declare your authService on app.module provider. 1 instance of authService for all your application.
Next you can do that :
<a *ngIf="!authService.isAuthenticated()" [routerLink]="['/login']">Login</a>

Private variables in Ember-data DS.Model

I want to store a private variable on each DS.Model. Its purpose is to store a pending callback (in case I want to cancel it).
I have tried this (and it works):
DS.Model.reopen({
init() {
let _pending; // my private var
this._getPending = () => _pending; // get private var
this._setPending = callback => _pending = callback; // set private var
this._super(...arguments);
}
});
I have placed this in an initializer, and it works as I expect it to.
My questions are: Is this a good practise? is it likely to mess anything up? ...and, is there a better way?
Personally, I'm happy with the way it works.. but I'm not sure if its the "Ember" way. This is going to go into an Ember-cli addon, so I would like it to be the most "best practise" as possible. (the _getPending/_setPending method are only to be used internally within the addon.)
Here are my 2 cents on this. I would say no it is not a good practice, but it should be okay since they are just Ember Objects. The question here is what is Ember data model used for? From doc it says:
"Models are objects that represent the underlying data that your application presents to the user."
By definition this is not what they are designed for, so just because you are able to it does not mean that you should use them like this.
Pending callback so it can be canceled? Ember model API has defined state objects that can be used for this purpose. http://emberjs.com/api/data/classes/DS.Model.html Flags like isDeleted, isValid, isNew...gives all possible state.
I would place them in router actions where they are easy tested with integration tests.
You can check this screencast that explains them:
https://www.emberscreencasts.com/posts/102-ember-data-20-model-states-and-flags
Hope it helps.

Remove data binding in angular2

Angular 2 data binding is great but i can't seem to find a angular 2 way of removing data binding on specific variables. My reason for this is i started hooking my application up to indexed DB and it works but i can't allow the temporary cache (just an array of all the indexed DB values) to be subject to data binding (if it was then the temporary cache would no longer mirror the database) my database is on an angular2 service. now i have found a way of removing the data binding but it isn't exactly pretty my code is this
app.copy=function(item){
return JSON.parse(JSON.stringify(item,app.replacer),app.reviver);
}
app.reviver=function(key,value){
if(value.fn){
value=new Function(value.parameters,value.body);
}else if(key==="time"){
value= new Date(value);
}
return value;
};
app.replacer=function(key,value){
if(typeof value ==="function"){
value=value.toString();
value={
fn:true,
parameters:value.match(/\(([\s\S]*?)\)/)[1].replace(/[\s\r\/\*]/g,""),
body:value.match(/\{([\s\S]*)\}/)[1].replace(/[\t\r\n]/g,"")
};
}
return value;
};
like i said it works but it isn't pretty. i can just run app.copy on the variables before they leave the cache so that they don't get data bound to anything. I was wondering if there was a cleaner way to tell angular 2 this variable isn't suppose to be data bound. and if not then at least i was able to get my solution up here for others.
If you establish "binding" imperatively you can stop the binding imperatively. There is currently no support in Angular2 to cancel a declarative binding imperatively.
Bind the view only to fields of the component.
Use observables in the service that fire an event when values change.
In the component subscribe to the observable and update the fields in the component when values in the service change.
Update values in the service when values change in the component.

How to inject state parameter automatically

Abstract
Hi, I'm using angular + ui-router in my project, I have huge amount of nested states and different views that in turn contain huge amount of different inputs, a user fills these inputs incrementally step by step.
The problem
Sometimes users require additional info that is located on the previous step, and browsers "back" button helps the user to sneak peek into that data, but as soon as the user presses it, the info he already entered is lost due to state transition, which is obviously a bad thing.
Strategy
In order to overcome described problem I have the following plan:
Associate each user's "navigation" (guess this is a proper term) with a random id
To prevent scope-inheritance-and-serialization issues, instead of putting viewmodel into $scope use ordinary javascript object that will be storing immediate values that are bound to UI.
Add watcher to look for changes on that "storage object"
As soon as the change spotted, serialize the object and persist it
Explanations
Why do we need a random parameter in URL?
We don't want to store all data in URL, since there might be quite some amount of data that wont fit into URL. So in order to provide the guarantees the URL won't break, we put only small random GUID/UUID into it that later allows obtaining the data associated with current "navigation" by this random GUID/UUID.
The storage
There are multitude of storage scenarios available out there: LocalStorage, IndexedDB, WebSQL, Session Storage, you name it, but due to their cross-tab, cross-browser, browser-specific nature it would be hard to manipulate and manage all of the data that gets into the storage. The implementation will be buggy / might require server-side support.
So the most elegant storage strategy for this scenario would be storing data in special window.name variable which is capable of storing data in-between requests. So the data is safe until you close your tab.
The Question
On behalf of everything written above, I have the root view called "view" that has a state parameter id (this is the random GUID/UUID)
$stateProvider.state('view', {
url: '/view/{id}',
controller: 'view',
templateUrl: 'views/view.html'
});
All of the other views derive from this view, is there way to make ui-sref directive to automatically inject a random GUID/UUID into id state parameter of my root view, instead of writing each time ui-sref's like:
<a ui-sref="view({id:guid()}).someNestedView({someNestedParam: getParam()})"
I would like to have something like:
<a ui-sref="view.someNestedView({someNestedParam: getParam()})"
The AOP and Decorator pattern are the answer. The comprehensive description could be found here:
Experiment: Decorating Directives by Jesus Rodriguez
Similar solution as described below, could be observed:
Changing the default behavior of $state.go() in ui.router to reload by default
How that would work? There is a link to working example
In this case, we do not solve from which source the random GUID comes from. Let's just have it in runtime:
var guidFromSomeSource = '70F81249-2487-47B8-9ADF-603F796FF999';
Now, we can inject an Decorator like this:
angular
.module('MyApp')
.config(function ($provide) {
$provide.decorator('$state', function ($delegate) {
// let's locally use 'state' name
var state = $delegate;
// let's extend this object with new function
// 'baseGo', which in fact, will keep the reference
// to the original 'go' function
state.baseGo = state.go;
// here comes our new 'go' decoration
var go = function (to, params, options) {
params = params || {};
// only in case of missing 'id'
// append our random/constant 'GUID'
if (angular.isUndefined(params.id)) {
params.id = guidFromSomeSource;
}
// return processing to the 'baseGo' - original
this.baseGo(to, params, options);
};
// assign new 'go', right now decorating the old 'go'
state.go = go;
return $delegate;
});
})
Code should be self explanatory, check it in action here

Upgrading a Model (backbone.js)

Right now I have a generic User model for all users. When a user logs it's determined wether they are user type 1 or user type 2. These two types need totally different models to represent them but still include everything found in the generic User model.
My goal is up upgrade the User model for each type of user by passing the state from the current User model into the Type1 or Type2 model.
(in coffeescript)
class Type1 extends User
#add super set of methods
#user arrives
user = new User
#after logging in
state = user.toJSON()
#do I need to unbind/delete the current user model?
user = new Type1(state)
Is this the best way to achieve this?
Thanks!
You could do that. You could also just copy over the attributes:
userCopy = new Type1
userCopy.attributes = user.attributes
delete user
Note that with either approach, you'll lose event bindings, etc. A safer, more JavaScript-y approach would be to just extend user in-place with additional methods, rather than having a Type1 class at all. (Of course, there are downsides to that to, such as losing the ability to invoke super from those methods. See my answer to a similar question here.)

Categories

Resources