你将如何捕获错误

How would you catch the error

在那种情况下,您将如何捕获错误:

   getStuff(): Observable<Stuff[]> {

    return this.http.get(url)
      .map((res: Response) => {
        return res.json()
        .map(item => {
          return {
            id: item.id
            name: item.code
          };
      });
    });

  }

我试着输入 .catch() 但说 return 类型不匹配 Supplied parameters do not match any signature of call target.

getStuff(): Observable<Stuff[]> {

    return this.http.get(url)
      .map((res: Response) => {
        return res.json()
        .map(item => {
          return {
            id: item.id
            name: item.code
          };
      });
    })
    .catch();

  }

.catch((err) => console.error(err)); 获得 Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<any>) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.

您可以使用 Observable.throw

function handleError(error: any) {

  let errorMsg = error.message || `Yikes! There was was a problem `;
  console.error(errorMsg);

  // throw an application level error
  return Observable.throw(errorMsg);
}

并使用

 .catch(handleError);