2016-10-14 4 views
2

ユーザーを認証するサービスがありますが、受け取ったデータの処理方法がわかりません。自分の役割に応じてユーザーを正しいページにリダイレクトするのではなく、ページに自分の名前を表示することをお勧めします。 私は別のものを試しましたが、私がルーターや機能を呼び出すと、決して見つけられません。それは同じ文脈にないように見えます。どうやってやるの ?ここでサービスの後に角2はsubscribeメソッドでアクションを実行できません

ログイン用コンポーネントです:

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

    } 
+0

を使用することができますか?ルータは未定義ですか?ルータはルートを見つけることができませんか? – Sefa

+0

それは大丈夫ですあなたは答えを見ることができます – fandro

答えて

4

あなたの問題は次の行です:.subscribe(function(result){ !!

これでfunction() -syntax this-scopeが失われます! .subscribe((result) => {

あなたは矢印構文() => ...このよう

を使用する必要があります。それだ

は、今は手段を「ルーターが見つかりされていない」ん何this.router.... :)

+1

ありがとう、それは完璧に動作します! – fandro

関連する問題