我使用http请求和rxjs在服务器上以角方式显示数据,但即使在导入rxjs的map属性之后,也会出现错误。
import { Injectable } from '@angular/core';
import {HttpClient,HttpHeaders,HttpErrorResponse} from '@angular/common/http';
import {throwError } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http:HttpClient) { }
registerUser(user){
let headers = new HttpHeaders();
headers.append('content-type','application/json');
return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
.map(response =>response.json())
.catch(this.errorHandler)
}
errorHandler(error:HttpErrorResponse){
return throwError(error.message||"Server not responding");
}}
我甚至像这样导入map属性:
import {map} from 'rxjs/add/operator';错误:
Property 'map' does not exist on type 'Observable<Object>'用户是一个对象
发布于 2019-03-24 06:30:17
如果您使用的是RXJS 6或更高版本,则运算符的用法发生了一些变化。
你通过以下方式进口:
import { map, catchError } from 'rxjs/operators';您可以在管道操作符内部使用映射,例如:
return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
.pipe(
map(response => {
// doSomething
}),
catchError(error => {
this.errorHandler(error);
return of(`Caught an error: ${error}`);
})
);发布于 2019-03-24 06:26:34
Observables上调用操作员。相反,使用Observable.pipe。rxjs/operators导入。HttpClient (来自@angular/common/http)将响应映射为JSON。不需要map操作符(这是Http (来自@angular/http)的前一种行为)。有关更正的示例,请参见下文:
import { /* imports go here */ } from '@angular/common/http';
// ...
// ...
export class AuthService {
// ...
registerUser(user){
let headers = new HttpHeaders();
headers.append('content-type','application/json');
return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
.catch(this.errorHandler);
}
}发布于 2019-03-24 06:29:15
如果使用的是RXJS 6或更高版本,则必须使用管道操作。
this.http.post('http://localhost:8080/users/register',user,{headers:headers})
.pipe(map(response => {
// do something with response and return it
})
catchError(this.errorHandler)
);另外,如果您使用的是HttpClient而不是Http,那么不需要使用response.json(),因为响应将被反序列化。
https://stackoverflow.com/questions/55321243
复制相似问题