Http发布并获得角度6的请求

问题描述 投票:23回答:2

在角度5.2.x的http get和post我有这个代码:

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中,它不起作用。

我们如何发布HTTP帖子或获取请求?

httprequest observable angular6
2个回答
34
投票

更新:在角度7中,它们与6相同

在角6

live example找到完整的答案

  /** 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现在angular能够使用tree-shakable并删除未使用的导入并优化应用程序

一些rxjs函数被更改

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

更多在MIGRATION

和导入路径

对于JavaScript开发人员,一般规则如下:

rxjs:创建方法,类型,调度程序和实用程序

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs /运算符:所有可管道运算符:

import { map, filter, scan } from 'rxjs/operators';

rxjs / webSocket:Web套接字主题实现

import { webSocket } from 'rxjs/webSocket';

rxjs / ajax:Rx ajax实现

import { ajax } from 'rxjs/ajax';

rxjs / testing:测试实用程序

import { TestScheduler } from 'rxjs/testing';

对于向后兼容性,您可以使用rxjs-compat


2
投票

你可以使用一个库来进行post / get,它允许你使用具有强类型回调的HttpClient。

可以通过这些回调直接获得数据和错误。

该库称为angular-extended-http-client。

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

非常好用。

传统方法

在传统方法中,您从Service API返回Observable <HttpResponse<T>>。这与HttpResponse有关。

使用这种方法,您必须在其余代码中使用.subscribe(x => ...)。

这会在http层和其余代码之间创建紧密耦合。

强类型回调方法

您只能在这些强类型回调中处理模型。

因此,您的其余代码只知道您的模型。

Sample usage

强类型回调是

成功:

  • 的IObservable <T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse <T>

失败:

  • IObservableError <TError>
  • IObservableHttpError
  • IObservableHttpCustomError <TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

并在@NgModule导入

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

在您的服务中,您只需使用这些回调类型创建参数。

然后,将它们传递给HttpClientExt的get方法。

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

在您的Component中,将注入您的服务并调用searchRaceInfo API,如下所示。

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

回调中返回的响应和错误都是强类型的。例如。响应是类型RacingResponse,错误是APIException。


0
投票

要在Angular中读取完整响应,您应该添加observe选项:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });
© www.soinside.com 2019 - 2024. All rights reserved.