httpClient请求在angular4中被调用两次

时间:2018-01-08 08:30:53

标签: angular apache-httpclient-4.x

我使用httpClient在我的angular4应用程序中调用API,但API调用两次,第一个调用方法是OPTIONS,第二个调用方法是Get。

Component.ts: -

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { UserService } from './Services/User.service';

@Component({
  selector: 'user-component',
  templateUrl: './user-component.component.html',
  styleUrls: ['./user-component.component.scss'],
  encapsulation: ViewEncapsulation.None
})

export class UserComponent implements OnInit {

  apiResponse : any;
  status      : any = 'active';

  constructor(private service: UserService) { } 

  ngOnInit() {
     this.getResult();
  }

  getResult()
  {
     this.service.getUser(this.status)
     .subscribe(res => {this.apiResponse = res},
                err => console.log(err),
                ()  => console.log(this.apiResponse)  
              );

  }
}

Component.html: -

<pre>{{apiResponse |json}}</pre>

User.service.ts: -

import { Injectable,Inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import 'rxjs/add/operator/map';

interface Response {
  response : any;
}

@Injectable()
export class UserService {
  apiUrl : any='http://localhost/MyProject/';
  constructor( private http: HttpClient) {}

  public getUser(status: any)
  {
     let httpParams = new HttpParams().set('status', status);
     return this.http.get<Response>(this.apiUrl+"users", {params: httpParams}).map(response => response.response);
  }
}

API被调用两次,请告诉我如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

OPTIONS次请求是自动的。你无法避免它。

From MDN

  

HTTP OPTIONS方法用于描述目标资源的通信选项。客户端可以为OPTIONS方法指定特定的URL,或者使用星号(*)来指代整个服务器。