我有一个服务来验证我的用户,但我不知道如何处理我收到的数据。我不想根据用户的角色将其重定向到正确的页面并在页面中显示其名称。
我尝试了不同的方法,但当我调用路由器或一个函数时,它永远找不到。看起来情况不一样。我该怎么做?
以下是我的登录组件:
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":"[email protected]", "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() {
}
}
最佳答案
您的问题如下:.subscribe(function(result){
!!
有了这个function()
-语法,this
-作用域就丢失了!
必须使用箭头语法() =>
。
像这样:.subscribe((result) => {
。
就这样,现在您可以使用this.router....
:)
关于angular - 服务调用后,Angular 2无法在subscribe方法中执行操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40040890/