如果您复制Angular的文档页面上公开的hero.service.ts类,则在调用catchError(this.handleError<any>('updateHero'))
时会发现问题。
错误是:
遵循完整的打字稿类:
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
答案 0 :(得分:-1)
我在这里找到了,我真的不明白为什么您也看不到错误。但这是在这里发生。
我更改了handleError的声明,参数的声明,并返回了Never类型。另外,我必须在记录期间更改错误对象的访问字段。
遵循最终代码:
/** 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;
}