cannot access to this of component in subscribe function

丶灬走出姿态 提交于 2019-12-11 05:57:20

问题


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)
                }
       );
     }
}

But by some reason 'this' is not a pointer to component but it's a subscribe. Does someone know the reason of issue?


回答1:


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



回答2:


Router.navigate doesn't take a components class instance as a parameter

this._router.navigate(link);

Is invalid.

It requires an array of route names

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

See also https://angular.io/docs/ts/latest/api/router/Router-class.html



来源:https://stackoverflow.com/questions/36688955/cannot-access-to-this-of-component-in-subscribe-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!