问题描述
在angular 5.2.x中,对于http get和post我有以下代码:
In angular 5.2.x for http get and post I had this code:
post(url: string, model: any): Observable<boolean> {
return this.http.post(url, model)
.map(response => response)
.do(data => console.log(url + ': ' + JSON.stringify(data)))
.catch(err => this.handleError(err));
}
get(url: string): Observable<any> {
return this.http.get(url)
.map(response => response)
.do(data =>
console.log(url + ': ' + JSON.stringify(data))
)
.catch((error: any) => Observable.throw(this.handleError(error)));
}
在角度6中,它不起作用.
In angular 6 it doesn't work.
我们如何发出HTTP帖子或获取请求?
How can we make an HTTP post or get request?
推荐答案
更新:在角度7中,它们与6相同.
Update :In angular 7, they are the same as 6
在角度6中
在实时示例
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
这是因为pipeable/lettable operators
的缘故,现在角度用户可以使用tree-shakable
并删除未使用的导入内容并优化应用程序
some rxjs functions are changed
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
和导入路径
对于JavaScript开发人员,一般规则如下:
For JavaScript developers, the general rule is as follows:
rxjs:创建方法,类型,调度程序和实用程序
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
rxjs/operators:所有可管道运算符:
rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
rxjs/webSocket:Web套接字主题实现
rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
rxjs/ajax:Rx ajax实现
rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
rxjs/testing:测试实用程序
rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';
为了获得向后兼容性,您可以使用rxjs-compat
and for backward compatability you can use rxjs-compat
这篇关于HTTP发布并在Angular 6中获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!