1

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Iva
  • 91
  • 2
  • 7

2 Answers2

4

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)
                }
       )
mohamedHabib
  • 196
  • 7
0

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    I cannot take this._router at all – Iva Apr 18 '16 at 08:44
  • 2
    Hard to tell because your question doesn't contain enough code. In your constructor you need `constructor(private _router:Router) {}`. – Günter Zöchbauer Apr 18 '16 at 08:46
  • 1
    Try adding `console.debug(this._router);` to your constructor to check if an instance is actually passed in. You can't inject `Router` in components that don't have routes. Instead inject `Router` to a global service and inject this service to your component. – Günter Zöchbauer Apr 18 '16 at 08:52