在调用服务后,Angular 2无法在订阅方法中执行操作

时间:2016-10-14 10:25:38

标签: angular typescript

我有一项服务来验证我的用户,但我不知道如何处理我收到的数据。我不想根据用户的角色将用户重定向到正确的页面,并在页面中显示他的名字。 我尝试了不同的东西,但当我打电话给路由器或功能时,它永远找不到。它看起来好像不在同一个环境中。我怎么能这样做?

这是我的登录组件:

  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() {
      }

    }

1 个答案:

答案 0 :(得分:4)

您的问题是以下行:.subscribe(function(result){ !!

使用function() - 语法,this - 范围会丢失!

您必须使用箭头语法() => ..

像这样:.subscribe((result) => {

那就是它,现在你可以使用this.router....:)