ارتقاء به HTTP Client در Angular 4.3
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۵/۲۳ ۱۴:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
npm install npm-check-updates -g ncu
ncu -a npm update
import { HttpModule } from '@angular/http'; import { HttpClientModule } from '@angular/common/http'; @NgModule({
imports: [
// ...
HttpClientModule,
// ...
],
declarations: [ ... ],
providers: [ ... ],
exports: [ ... ]
})
export class AppModule { } constructor(private http: Http) { } import { HttpClient } from '@angular/common/http';
// ...
constructor(private http: HttpClient) { } public get(): Observable<MyType> => {
return this.http.get(url)
.map((response: Response) => <MyType>response.json());
} get<T>(url: string): Observable<T> {
return this.http.get<T>(url);
} post<T>(url: string, body: string): Observable<T> {
return this.http.post<T>(url, body);
} getData() {
this.http.get(this.url, { responseType: 'text' }).subscribe(res => {
this.data = res;
});
} {
"results": [
"Item 1",
"Item 2",
]
} this.http.get('/api/items').subscribe(data => {
this.results = data['results'];
}); import { HttpHeaders } from "@angular/common/http";
const headers = new HttpHeaders({ "Content-Type": "application/json" }); const headers = new HttpHeaders().set("Accept", "application/json").set('Content-Type', 'application/json'); updateAppProduct(id: number, item: AppProduct): Observable<AppProduct> {
const header = new HttpHeaders({ "Content-Type": "application/json" });
return this.http
.put<AppProduct>(
`${this.baseUrl}/UpdateProduct/${id}`,
JSON.stringify(item),
{ headers: header }
)
.map(response => response || {});
} (method) HttpClient.post(url: string, body: any, options?: {
headers?: HttpHeaders;
observe?: "body";
params?: HttpParams;
reportProgress?: boolean;
responseType?: "json";
withCredentials?: boolean;
}): Observable<Object> const headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Accept', 'application/json'); const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
; http
.post('/api/items/add', body, {
params: new HttpParams().set('id', '3'),
})
.subscribe(); /api/items/add?id=3
const params = new HttpParams();
params.set('orderBy', '"$key"')
params.set('limitToFirst', "1"); const params = new HttpParams()
.set('orderBy', '"$key"')
.set('limitToFirst', "1"); const params = new HttpParams({fromString: 'orderBy="$key"&limitToFirst=1'}); import { HttpClient, HttpHeaders, HttpErrorResponse } from "@angular/common/http";
postData() {
this.http.post(this.url, this.payload).subscribe(
res => {
console.log(res);
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.name);
console.log(err.message);
console.log(err.status);
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {
console.log("Server-side error occured.");
}
}
);
} import 'rxjs/add/operator/retry';
http
.get<ItemsResponse>('/api/items')
.retry(3)
.subscribe(...); (method) HttpClient.post(url: string, body: any, options?: {
headers?: HttpHeaders;
observe?: "body";
params?: HttpParams;
reportProgress?: boolean;
responseType?: "json";
withCredentials?: boolean;
}): Observable<Object> http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
console.log(resp.headers.get('X-Custom-Header'));
console.log(resp.body.someField);
}); this.http.get( this .url, { responseType: 'blob' } ) @Injectable()
export class FormPosterService {
private baseUrl = "http://localhost:5000/api/Ngx";
constructor(private http: HttpClient) { }
postUserForm(form: LoginForm): Observable<LoginForm> {
const headers = new HttpHeaders({ "Content-Type": "application/json" });
return this.http
.post<LoginForm>(`${this.baseUrl}/login`, form, { headers: headers, withCredentials: true /* For CORS */ });
}
} doRefreshToken(refreshToken: string): Observable<any> {
const body = new HttpParams()
.set('grant_type', "refresh_token")
.set('refresh_token', refreshToken);
return this.http.post('/login',
body.toString(),
{
headers: new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
}
);
} Unexpected token o in JSON at position 1 at JSON.parse
this.http.get(url).subscribe(result => {
const item = result['results'][0];
this.lat = item.geometry.location.lat;
this.lng = item.geometry.location.lng;
this.zoom = 15;
},
error => {}
);