标签: angular-httpclient

热与冷可观测量

在RxJS中,热观测值是使用外部生产者的可观测量,但冷观测值使用当地生产者(参见例如Ben Lesh的RxJS Hot vs Cold Observable).

Angular HttpClient.post使用冷可观察量来发送数据并在您拨打电话时重复.

在Angular中是否有任何方法可以知道特定方法是使用热观察还是冷观察?

rxjs angular angular-httpclient

8
推荐指数
1
解决办法
2126
查看次数

Angular 模拟多个 HTTP 调用

我有一项服务,它返回多个 http 调用的 forkjoin。我想测试这个场景。

    class CommentService{
     addComments(){

let ob1 = Observable.of({});
    let ob2 = Observable.of({});
if(any condition)
        ob1 = {this.http.post('/url/1')};
if(any condition)
            ob2 = {this.http.post('/url/2'};
        return Observable.forkJoin(ob1,ob2)
           }
     }
Run Code Online (Sandbox Code Playgroud)

以上是我的服务类。我如何模拟 http 调用。

describe("CommentService", () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, HttpClientTestingModule],
      providers: [CommentService]
    });

    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('addComments() call with normal and gate', inject([CommentService], (service: CommentService) => {


    let cmts = service.addComments();

    const reqGateComment = httpTestingController.expectOne('/url/1');
    expect(reqGateComment.request.method).toEqual('POST');

    const …
Run Code Online (Sandbox Code Playgroud)

rxjs typescript karma-jasmine angular angular-httpclient

8
推荐指数
1
解决办法
3071
查看次数

Angular HttpClient 可观察到未完成

我有以下代码:

// in a service
downloadCSV(): Observable<Blob> {
  return this.httpClient.get(`${apiUrl}/a.csv`, {responseType: 'blob'});
}
// in component
onDownloadClicked(event: MouseEvent) {
  this.downloading = true;
  this.service.downloadCSV()
    .pipe(finalize(() => this.downloading = false))
    .subscribe(
      (data: Blob) => {
        console.log(data);
      },
      (error) => {
        console.error(error);
        alert('Sorry, something wet wrong. Try again.');
      },
      () => {
        console.log('completed!');
      }
    );
}
Run Code Online (Sandbox Code Playgroud)

数据已正确记录,但“已完成!” 不记录并且永远不会调用 Finalize。

编辑:

因此,经过进一步调查,问题似乎与添加 auth 标头的拦截器有关。

如果拦截器被绕过(并且在服务器上禁用了身份验证),则可观察对象将完成而不会出现错误。

我不明白为什么会发生这种情况。可能与请求被克隆有关?

//interceptor code
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let scope: string;
  // only inject tokens for the following …
Run Code Online (Sandbox Code Playgroud)

javascript observable rxjs angular angular-httpclient

8
推荐指数
1
解决办法
3266
查看次数

Angular HttpClient为零响应返回null值

我已将Angular 4服务从旧的Http迁移到新的HttpClient.返回纯零0作为响应的请求正在返回一个observable null.

请求:

return this.httpClient.get(url, options)
  .do(res => console.log('service returns', res)) as Observable<number>;
Run Code Online (Sandbox Code Playgroud)

将控制台日志null,但当我在devtools>网络中打开该请求时,我看到服务器响应0.

我究竟做错了什么?

angular angular-httpclient

7
推荐指数
1
解决办法
3439
查看次数

405 方法不允许,尽管 CORS

我正在尝试使用 Angular 开发前端应用程序。由于我向HTTP POST 和 GET 请求添加了授权标头,因此我收到了405 Method Not Allowed,尽管我似乎允许服务器端的所有内容。

在此处输入图片说明

我的浏览器 Chrome 中的调试器说它要求Access-Control-Request-Method: POSTAccess-Control-Request-Headers: authorization,我的后端允许同时,access-control-allow-methods: GET, POSTaccess-control-allow-headers: authorization,以及access-control-allow-credentials: true

我不明白我在这里缺少什么。服务器是一个 node.js express 服务器,标头设置如下:

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Headers', 'authorization');
Run Code Online (Sandbox Code Playgroud)

前端代码(Angular 5)如下所示:

this.http.request('post', apiUrl, {
  headers: new HttpHeaders().set('Authorization', 'Bearer abc'),
}).subscribe(response => {
  // some code
});
Run Code Online (Sandbox Code Playgroud)

哪里this.http是角的实例HttpClient

我的前端应用程序是从我的本地主机域“ http://frontend.localhost/app ”提供的,我的后端服务器位于“ http://backend.localhost ”。

我的问题是,我是否缺少一些必须在后端设置的标头?我需要在我的前端应用程序中设置一些选项吗?

http xmlhttprequest http-headers cors angular-httpclient

7
推荐指数
1
解决办法
2万
查看次数

Angular HttpClient 流

我正在为 Cordova/iOS 开发一个 Angular 应用程序。我从后端服务获得了大约 100 MB 的数据,这似乎让 iOS 的网络视图 (WKWebView) 崩溃了。至少我没有遇到返回较少数据的测试后端崩溃。

数据将存储在 IndexedDB 中,因此没有理由用所有这些数据填充 RAM。

所以我的想法是将响应直接流式传输到 IndexedDB 中。有可用的库即使使用 JSON 也可以做到这一点,例如Oboe.jsJSONStream

AngularHttpClient以大字符串或 JSON 对象的形式返回整个响应,这不是我想要的。有没有一种方法可以逐步处理类似于此的响应:https : //stackoverflow.com/a/18964123/395879

ajax xmlhttprequest angular angular-httpclient

7
推荐指数
1
解决办法
1408
查看次数

带主体的Angular HttpClient Get方法

我正在改进现有的API,并且要求提供一种可以接受多个搜索条件并基于这些条件执行查询的单一get方法。

我正在使用Spring MVC。get方法签名:

@GetMapping("/subscribers")
public ResponseEntity<List<SubscriberDTO>> getAllSubscribers(Pageable pageable, @RequestBody List<SearchCriteria> lstSearchCriteria)
Run Code Online (Sandbox Code Playgroud)

该实现按预期在邮递员上进行了测试

现在我要去Angular实现前端,但是我找不到通过HttpClient Get方法发送正文的方法。

我有点卡住。我应该在标题上发送搜索条件吗?还是有更好的方法呢?

angular angular-httpclient

7
推荐指数
4
解决办法
8833
查看次数

Angular HttpClient请求方法如何设置正文

我需要发送带有正文的获取请求。我使用的是 Angular HttpClient。我知道 get 方法不允许发送正文,所以我正在尝试请求方法,但我不明白如何使用它。

我能够在没有正文部分的情况下从下面的示例中获取数据,但我确实需要以 JSON 格式发送正文。

    request(req?: any): any{

    const options = createRequestOption(req);
    return this.http
        .request<ISubscriber[]>("GET", this.resourceUrl,
        {
            body: '[{"key": "phoneLineType", "operation": ">", "value": "200"}]',
            headers: new HttpHeaders({'Content-Type' : 'application/json'}),
            params: options,
            observe: 'response'
        });
}
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

7
推荐指数
1
解决办法
2万
查看次数

角度测试 HTTP Post 调用

我有一个 angular 组件,它将一些数据发布到我们应用程序中的 URL,然后什么都不做,因为没有数据从该帖子返回。我在测试这个时遇到了麻烦,因为通常 HTTP 请求是通过订阅它们返回的 observable 来测试的。在这种情况下不需要暴露。

这是我的组件代码:

shareData(): void {
    this.isFinishing = true;
    this.myService.sendSharedData$()
        .pipe(first())
        .subscribe(() => {
            //Data s now shared, send the request to finish up everything
            this.submitFinishRequest();
        }, (e: Error) => this.handleError(e)));
}

private submitFinishRequest(): void {
    //submit data to the MVC controller to validate everything,

    const data = new FormData();
    data.append('ApiToken', this.authService.apiToken);
    data.append('OrderId', this.authService.orderId);

    this.http.post<void>('/finish', data)
        .pipe(first())
        .subscribe((d) => {
            // The controller should now redirect the app to the logged-out MVC view, so …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular angular-httpclient angular-test

7
推荐指数
1
解决办法
6774
查看次数

如何跨模块创建HttpInterceptor?

我对HttpInterceptors 上 Angular 文档底部的使用说明很好奇,它指出:

要为整个应用程序使用相同的 HttpInterceptors 实例,请仅在 AppModule 中导入 HttpClientModule,并将拦截器添加到根应用程序注入器。如果跨不同模块多次导入 HttpClientModule(例如,在延迟加载模块中),则每次导入都会创建 HttpClientModule 的新副本,这会覆盖根模块中提供的拦截器。

我不明白该怎么做。如何获取根应用程序注入器并将我的延迟加载模块的 HttpInterceptor 添加到其中?

似乎How to import Angular HTTP拦截器仅适用于子模块也试图回答这个问题,但答案对我来说同样不清楚。

为什么这不起作用,以及如何正确添加第二个延迟加载拦截器?

应用程序模块

@NgModule({
  imports: [RouterModule.forRoot(routes)], // routes contains a lazy load module
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi: true,
    }
  ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

延迟加载子模块

@NgModule({
  imports: [
    LazyRoutingModule
  ],
  declarations: [ChildComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CacheInterceptorService,
      multi: true,
    }
  ]
}) …
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular angular-httpclient

7
推荐指数
1
解决办法
7416
查看次数