Angular rxjs5中的Rxjs6:在RESTAPI方法中处理可观测值

Angular rxjs5中的Rxjs6:在RESTAPI方法中处理可观测值,angular,rxjs6,Angular,Rxjs6,我是rxjs和Angular的新手,我刚刚发现(多亏我的WebStorm给了我大量的红色错误消息),rxjs5与版本6有很大的不同 因此,我将遵循这一点,指导用户使用rxjs组装API服务。问题是,它是为版本5编写的 下面是用版本5编写的API路由示例: public getAllTodos(): Observable<Todo[]> { return this.http .get(API_URL + '/todos') .map(response => {

我是rxjs和Angular的新手,我刚刚发现(多亏我的WebStorm给了我大量的红色错误消息),rxjs5与版本6有很大的不同

因此,我将遵循这一点,指导用户使用rxjs组装API服务。问题是,它是为版本5编写的

下面是用版本5编写的API路由示例:

public getAllTodos(): Observable<Todo[]> {
  return this.http
   .get(API_URL + '/todos')
   .map(response => {
     const todos = response.json();
     return todos.map((todo) => new Todo(todo));
   })
   .catch(this.handleError);
}
public getAllTodos():可观察{
返回此文件。http
.get(API_URL+/todos)
.map(响应=>{
const todos=response.json();
返回todo.map((todo)=>newtodo(todo));
})
.接住(这个.把手错误);
}
阅读文档后,我重新编写了第6版的路径:

public getAllTodos(): Observable<Todo[]> {
  return this.http
   .get(API_URL + '/todos')
   .pipe(
     map(response => {
      return response.map((todo) => new Todo(todo));
     }),
     catchError(this.handleError)
  );
}
public getAllTodos():可观察{
返回此文件。http
.get(API_URL+/todos)
.烟斗(
映射(响应=>{
返回response.map((todo)=>newtodo(todo));
}),
catchError(this.handleError)
);
}
问题是,我得到了:

类型“Object”上不存在属性“map”


我猜这与响应不是json格式有关,尽管响应似乎没有.json()方法。

出现错误的原因是,如果您没有指定
响应
变量的类型,则假定它是一个对象。由于
map
是一个数组函数,您需要将响应类型指定为数组:

this.http.get<any[]>(...).pipe(...); // Preferred

请注意,您应该用API返回的实际类型(字符串、对象等)替换上面的
任何

出现错误的原因是,如果您没有指定
响应
变量的类型,则假定它是一个对象。由于
map
是一个数组函数,您需要将响应类型指定为数组:

this.http.get<any[]>(...).pipe(...); // Preferred

请注意,您应该用API返回的实际类型(字符串、对象等)替换上面的
any

pipe(tap(v=>console.log(v)))
是您的朋友。在该阶段检查您可以观察到的任何内容,并相应地调整代码。对于angular,惯用的方法(使用HttpClient)是
返回这个.http.get(url).pipe(map(res=>res.map(todo=>new todo(todo)),catchError(handleErr));
-注意通用的
get
管道(tap(v=>console.log(v)))
是你的朋友。检查你在那个阶段观察到的任何东西,并相应地调整代码。对于angular,惯用的方法(使用HttpClient)是
返回这个.http.get(url).pipe(map(res=>res.map(todo=>new todo(todo)),catchError(handleErr));
-注意通用的
get