catchError of sample "https://angular.io/tutorial/toh-pt6" не работает - PullRequest
0 голосов
/ 30 декабря 2018

Если вы скопируете класс hero.service.ts, представленный на странице документов Angular, вы увидите проблему при вызове catchError(this.handleError<any>('updateHero')).

Ошибка:

enter image description here

Следуйте полному классу машинописи:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { Hero } from './hero';
import { MessageService } from './message.service';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({ providedIn: 'root' })
export class HeroService {

  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(
    private http: HttpClient,
    private messageService: MessageService) { }

    /** PUT: update the hero on the server */
      updateHero (hero: Hero): Observable<any> {
        return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
          tap(_ => this.log(`updated hero id=${hero.id}`)),
          catchError(this.handleError<any>('updateHero'))
        );
      }
    /**
       * Handle Http operation that failed.
       * Let the app continue.
       * @param operation - name of the operation that failed
       * @param result - optional value to return as the observable result
       */
      private handleError<T> (operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {

          // TODO: send the error to remote logging infrastructure
          console.error(error); // log to console instead

          // TODO: better job of transforming error for user consumption
          this.log(`${operation} failed: ${error.message}`);

          // Let the app keep running by returning an empty result.
          return of(result as T);
        };
      }

      /** Log a HeroService message with the MessageService */
      private log(message: string) {
        this.messageService.add(`HeroService: ${message}`);
      }
    }

Следуйте за ошибкой:

Argument type (error:any)=>Observable<Cart> is not assignable to parameter type (err:any, caught:Observable<T>)=> never

1 Ответ

0 голосов
/ 30 декабря 2018

Я разобрался здесь, я действительно не понимаю, почему вы тоже не могли увидеть ошибку.Но это происходило здесь.

Я изменил объявление handleError, параметров и возвращал тип никогда.Также мне пришлось изменить поля доступа объекта ошибки во время регистрации.

Следуйте окончательному коду:

/** POST: add a new hero to the server */
  save(): Observable<Hero> {

    var o : Observable<Hero>=this.http.post<Hero>(
        "http://localhost/FoodMail/master/src/webservice.php?q=SalEBrasa", c, httpOptions)
        .pipe(
            tap((hero: Hero) => {this.log(`added hero w/ id=${hero.id}`)}),
            catchError<Hero>(this.handleError2.bind(this))
        );
    o.subscribe();
    return o;
  }
  private  handleError2<T>(error: any, caught: Observable<T>) : never{


    // TODO: send the error to remote logging infrastructure
    console.error(error.message); // log to console instead

    // TODO: better job of transforming error for user consumption
    this.log(`${error.statusText} failed: ${error.message}`);

    // Let the app keep running by returning an empty result.
    //return of(err as T);
    throw  error;

  }
...