Angular 在角度传感器中未检测到404

Angular 在角度传感器中未检测到404,angular,Angular,我有一个Angular应用程序,如果我的API返回404状态码,我会尝试重定向到一个页面。我试图用下面的方法捕获错误,如果是404,则推到另一个页面 ngOnInit(){ this.auth.memberInfo() .subscribe(res =>{ this.user = res.json(); console.log('The User: ', res.json()); this.profileService

我有一个Angular应用程序,如果我的API返回404状态码,我会尝试重定向到一个页面。我试图用下面的方法捕获错误,如果是404,则推到另一个页面

  ngOnInit(){
    this.auth.memberInfo()
      .subscribe(res =>{
        this.user = res.json();
        console.log('The User: ', res.json());
        this.profileService.getProfile(res.json().id)
          .subscribe(res => {

            if(res.status === 404){
              this.navCtrl.push('CreateProfilePage');
            } else {
              this.profile = res.json();

              if(this.profile.first_name && this.profile.last_name)
                this.profileInitials = this.profile.first_name.charAt(0) + this.profile.last_name.charAt(0);
            }

          })

      })
  }
出于某种原因,此检查不起作用,我也没有处理错误


有人知道我做错了什么吗?

最有效的方法是使用拦截器。只需这样声明您的拦截器:

找不到.interceptor.ts

现在,对于您发送的任何HTTP调用,若您将返回404,它将把用户重定向到您的404页面。您可以将此方法用于许多事情,例如:

401响应上的未授权用户 禁页 全局错误处理 你可以说:
添加整个脚本plz如果在订阅中使用console.logres,您会得到什么?因为我从api返回404状态,所以我得到以下控制台结果:响应{{u body:{msg:No profile found},状态:404,ok:false,状态文本:Not found,headers:headers,}哦,您需要在catch参数中添加处理部分,如下所示:this.auth.memberInfo.subscriberes=>{},err=>{//handle the error here}谢谢,Hussein,这样做了。
import {Injectable} from '@angular/core';
import {
  HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Router} from '@angular/router';
import 'rxjs/add/operator/catch';
import {ErrorObservable} from 'rxjs/observable/ErrorObservable';

@Injectable()
export class NotFoundInterceptor implements HttpInterceptor {
  constructor(private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req)
      .catch((response: HttpErrorResponse) => {
        if (response.status === 404) {
          this.router.navigate('/your-404-route');
        }

        return ErrorObservable.create(response);
      });
  }
}
providers: [
...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: NotFoundInterceptor,
      multi: true
    }
...
  ],