3

this is my service :

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { Router} from '@angular/router';
@Injectable()

export class LoginService {
constructor(private http: Http, public router: Router){}

  login1( loginParams: any ){
    let params = new URLSearchParams();
    params.set('login', loginParams.login);
    params.set('password', loginParams.password);
    let loginUrl = 'api/admins/login';
    return this.http
                .post(loginUrl, params)
                .map(this.extracData)
                .catch(this.handleError);
  }
....
 private extracData( res: Response ){
    // console.log(res.json());
    let body = res.json();
    console.log(body.statusCode);
    if (body.statusCode == 404) {
      this.router.navigate(['/error', 404]);
      // return false;
    }
    return body || {};
  }

  private handleError( error: any ){
    let errMsg = (error.message)?error.message:
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.log(error.status);
        return Observable.throw(errMsg);
  }

}

then ,when the body.statusCode is 404 ,it can't navigate 404 page,but process handleError function, so ,i dont't know why angular2 dont't process navigate function ?

and that's my error routes

{
    path: 'error/:id',
    component: errorComponent
  }
Charles
  • 123
  • 2
  • 2
  • 9
  • How does your app.module looks like? – John Jan 06 '17 at 02:58
  • @John what's mean? i think it's nothing about app.module. – Charles Jan 06 '17 at 03:05
  • When you navigate to /error , you should have a path match in your app.module that matches that path to navigate to your Component to display – John Jan 06 '17 at 03:06
  • @John yes, i define it in routes and declare in app.moudule, i test in browser ,it could be opened in browser, and if i process 404 page in component, it can navigate to 404 page, only not navigate in service! – Charles Jan 06 '17 at 03:10
  • Then my guess is that a 404 is an error which is being catched, and you should do the navigation i the handleError method. The extracData is not called in that case – John Jan 06 '17 at 03:15
  • @John, first of all, i think so, then i move the 404 code to handleError method ,then it can't handle handleError function! so ,this is a success request! – Charles Jan 06 '17 at 03:23
  • Ok. Then I am not sure why it is failing. Maybe the navigation is redirecting you to the same loginService, meaning that you are navigating, but after the navigation, you handle the error. Just a wild guess. – John Jan 06 '17 at 03:26
  • in fact , i firstly search the results that how to use navigate in Injectable service, some results tell me that it can't use in service, but i don't why,and i think it can use in service! – Charles Jan 06 '17 at 03:30

0 Answers0