1

So, im quite new with angular 2, so far so good. The problem that im having (may be because so use to angular 1) is that i need the class user to be global and use it between diferent components.

in my case i got a User class and im login the user in one component.

@Component({
  selector: 'login',
  templateUrl: 'app/login/login.html',
  providers: [User]
})
export class loginComponent {
  submitted = false;
  username  : string;
  password  : string;
  constructor(public user : User){}
  onSubmit(event) { //form event
    event.preventDefault();
    this.user.login(this.username,this.password, () =>{this.router.navigateByUrl('dashboard')}

So the method login in user is setting the internal variables of user, like name, last name, etc. in the router i have a diferent component asigned to the route dashboard. so when i import User i got a new instance of the class. how can i mantain the data in the class?

3
  • Don't declare the User in the component's providers. Declare it in the root NgModule's providers. Commented Aug 24, 2016 at 21:24
  • ...i dont have, a ngModule, im bootstraping a mainComponent...like the documentation says...i injected the providers on that component and worked, i guess is like the old scope thing with angular 1 Commented Aug 24, 2016 at 21:26
  • That must be old documentation you're looking at then. Read angular.io/docs/ts/latest/guide/ngmodule.html. But you'll have the same effect if you declare it in the providers of the root component. Commented Aug 24, 2016 at 21:28

1 Answer 1

2

First I would suggest use 'UserService' rather User.

You are looking for Application-wide dependencies, That needs to be provided at a Higher Level, preferably in your AppComponent or AppModule.

In a nutshell in your application wherever you add a service in providers array, a new instance will be used in that component and any child components.

Hence you are getting new instance of the service, when you define provider in AppComponent and not in loginComponent, the same instance can be injected there.

Hope this helps!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.