无法访问订阅功能中的组件
问题描述:
从服务器获取答案时,我正在尝试导航到新页面:
I'm trying navigate to new page when get answer from server:
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"不是指向组件的指针,而是订阅. 有人知道问题的原因吗?
But by some reason 'this' is not a pointer to component but it's a subscribe. Does someone know the reason of issue?
答
我认为您应该在调用http帖子之前缓存此变量,因为在订户内部这是指订户本身.
I think you should cache the variable this before calling the http post, because inside the subscriber this refer to the subscriber itself.
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)
}
)