无法访问订阅功能中的组件

cannot access to this of component in subscribe function

我正在尝试从服务器获得答案时导航到新页面:

import {Component} from '../../node_modules/angular2/core';
import {Router} from "../../node_modules/angular2/router";
import {Http, Headers, HTTP_PROVIDERS} from '../../node_modules/angular2/http'

@Component({
    selector: 'test-page',
    templateUrl:'src/login/test.html',
    providers: [HTTP_PROVIDERS]
})


export class TestPage {
    constructor(private _router:Router,
                private _http:Http) {
    }

    Test(username, password) {
        let body = 'test';
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this._http.post('/api/test', 'test', {headers: headers})
        .subscribe(
                response => {
                    this._router.navigateByUrl('Home'); //'this' is not a component
                },
                error => {
                   console.log(error)
                }
       );
     }
}

但由于某种原因 'this' 不是指向组件的指针,而是订阅。 有人知道问题的原因吗?

Router.navigate 不将组件 class 实例作为参数

this._router.navigate(link);

无效。

它需要一个路由名称数组

this._router.navigate(['MyRoute']);

另见 https://angular.io/docs/ts/latest/api/router/Router-class.html

我认为您应该在调用 http post 之前缓存变量 this,因为在订阅者内部 this 指的是订阅者本身。

let headers = new Headers();
var self = this;
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('/api/test', 'test', {headers: headers})
       .subscribe(
                response => {
                    self._router.navigate(link); 
                },
                error => {
                   console.log(error)
                }
       )