Angular, Http GET with parameter?

2020-01-30 08:11发布

问题:

I dont know how to make an API call to such a method:

[HttpGet]
[ActionName("GetSupport")]
public HttpResponseMessage GetSupport(int projectid)

Because it is GET but still got a parameter to pass, how to do this? Would it be something like this?

let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      headers.append('projectid', this.id);

      this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers })

回答1:

Having something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('projectid', this.id);
let params = new URLSearchParams();
params.append("someParamKey", this.someParamValue)

this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers, search: params })

Of course, appending every param you need to params. It gives you a lot more flexibility than just using a URL string to pass params to the request.

EDIT(28.09.2017): As Al-Mothafar stated in a comment, search is deprecated as of Angular 4, so you should use params

EDIT(02.11.2017): If you are using the new HttpClient there are now HttpParams, which look and are used like this:

let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams

And then add the params to the request in, basically, the same way:

this.http.get(url, {headers: headers, params: params}); 
//No need to use .map(res => res.json()) anymore

More in the docs for HttpParams and HttpClient



回答2:

I am assuming you are using some angular2 service. You can call HTTP with params like below

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class MockService {
    constructor(public http: Http) {
  }

 getFakeUser(pageNumber) {
    let URL = "https://randomuser.me/api/?page=" + pageNumber + 
        "&results=10&inc=name,gender,nat,picture&noinfo";
    return new Promise((resolve, reject) => {
      this.http.get(URL)
          .map(res => res.json())
          .subscribe(data => {
              // console.log(data)
             resolve(data);
           }, (error => {
              reject(error);
            }));
         });
        }
    }