服务角度11中的管理错误问题

时间:2021-05-09 06:39:37

标签: angular

嗨,我想修复错误并在发生错误时在 appComponent 中获取错误。但是先输入res再输入Error。我该如何解决这个问题?

我要当我遇到错误时,不要再在组件中输入Res,直接输入错误

应用服务:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operator/map';

@Injectable()
export class AppService {
  constructor(private http:HttpClient){}
  run() {
    console.log('app service')
  }
  postData(data:string):Observable<any>{
    return this.http.post('',data)
    .pipe(
      map((data:any)=>{
        return this.success(data);
      }),
      catchError(error=>{
        this.error(error);
        return throwError('error');
      })
    )
  }
  success(data){
      // Other commands
    // ... 
    // ...
    return data;
  }
  error(error){
    // Other commands
    // ... 
    // ...
    return error;

  }
}

appComponent:

import { Component } from '@angular/core';
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';
  constructor(private service:AppService){
     this.sendDate()
  }
  sendDate(){
    this.service.postData('test').subscribe(
      res=>{
        console.log("OK")
      },
      error=>{
        console.log("--NOK--")
      }
    )
  }
}

控制台:

OK
OK
post http://url 500(internal server error)
OK
OK
--NOK--

0 个答案:

没有答案