fandro fandro - 1 month ago 5
TypeScript Question

Angular 2 can't do actions in subscribe method after service called

I have a service to authenticate my user but I don't know what to do with the data that I received. I wan't to redirect the user to the correct page depending of his role and display his name in the page.
I tried different things but when I called the router or a function it's never find. It look's like it's not in the same context. How can I do that ?

Here is my login component :

import { Component, OnInit } from '@angular/core';
import {User} from "../models/user";
import {AuthenticationService} from "../services/authentication.service";
import {Router} from "@angular/router";

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthenticationService]
})
export class LoginComponent implements OnInit {

user:User = new User();
result: any;

constructor(private authenticationService:AuthenticationService,
private router:Router) {
}

loginAction(){
this.authenticationService.login(this.user)
.subscribe(function(result){
this.result = result;
console.log(this.result); // result : {token: "ABCDE....", "email":"test@test.com", "username": "Jack James", role:"ADMIN"}
this.doSth(); //Never called I supposed it's not the same context
this.router.navigate(['home']); // router is not find
// I wan't to do actions to redirect to another page and display the user currently logged in
},
err => {
// Log errors if any
console.log(err);
});
}

doSth(){
console.log("Do something");
}

ngOnInit() {
}

}

Answer

Your problem is following line: .subscribe(function(result){ !!

With that function()-syntax the this-scope is lost!

You have to use the arrow-syntax () => ..

Like this: .subscribe((result) => {.

That's it, now you can use this.router.... :)

Comments