使用参数进行Get请求

时间:2020-08-03 20:32:00

标签: angular typescript typescript1.8 http-request-parameters

我想用Angular Typescript编写此请求:

http://localhost:8080/engine/oauth/authorize?client_id=admin&redirect_uri=http://localhost:9000/callback&response_type=code&scope=read_profile

当我在网络浏览器中打开此链接时,我得到重定向响应:

http://localhost:9000/callback?code=7CLwgh 

我尝试编写此Typescript代码:

authCodeRequest(name: string, password: string): Observable<any> {
    const body = new HttpParams()
      .set('client_id', 'admin')
      .set('redirect_uri', 'http://localhost:9000/callback')
      .set('response_type', 'code')
      .set('scope', 'read_profile');
    const headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    return this.httpClient
      .get(environment.api.urls.auth.token, body.toString(), {
        headers
      })
      .pipe(
        map((response: Authorize) => {
          console.log(data)
          return true;
        })
      );
  }

对于get请求,我得到此错误:TS2554:预期有1-2个参数,但有3个。

发出请求并从重定向的链接参数code获取结果的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您正在尝试执行POST,但实际上是在执行GET。 将httpClient.get替换为httpClient.post。

如果您确实要执行GET,则不能使用x-www-form-urlencoded。您的请求参数将添加到请求URL。

let params= new HttpParams()
  .set('client_id', 'admin')
  .set('redirect_uri', 'http://localhost:9000/callback');
let options = { params: params };
return this.httpClient
  .get(environment.api.urls.auth.token, options)
  .pipe();