Angular8&9 | Http get将params字符串添加到查询字符串

问题描述 投票:0回答:1

我是Angular的新手。我尝试使用http get方法发送数据,但将param:"{param}"添加到查询字符串中会导致服务器端错误。我使用Mozilla开发人员工具删除了param,然后重试,其工作原理。

我的问题是为什么angular要在查询字符串中添加param:"{param}"以及如何删除它。请在下面找到代码。

enter image description here

组件

import { HttpParams } from '@angular/common/http';

@Component({
  //removed for readability
})
export class HttpRequestComponent implements OnInit {

  requestParam = new HttpParams();;

  constructor(
    private httpRequestService: HttpRequestService,
    private _snackBar: MatSnackBar) {
      this.requestParam = this.requestParam.set("page", "0");
      this.requestParam = this.requestParam.append("row_size", "20");
  }

  ngOnInit() {
    console.log(history.state);
    this.link = history.state.link;
    this.readAllData();
  }

  readAllData() {
    return this.httpRequestService.readAllData(this.link, this.requestParam).subscribe(
      result => {
        if (result.status=="SUCCESS") {
          this._snackBar.open('Record found. Code:'+result.data, 'Read', {
            duration: 3000,
          });
        } else {
          this._snackBar.open('Something went wrong while reading record.', 'Read', {
            duration: 3000,
          });
        }
      },
      error => console.error(error),
      () => {}
    );
  }
}

服务

import { HttpHeaders, HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpRequestService {

  httpOptions = {
    headers: new HttpHeaders({ 
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient) { }

  readAllData(link, request_param): Observable<any> {
    return this.http.get<any>(link, {observe:"events", params: request_param, responseType: "json"})
      .pipe(
        tap(_ => console.log('Read all URI')),
        catchError(this.handleError<any>('readAllData', []))
      );
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }
}
angular angular8 angular9
1个回答
0
投票

我看不到您的代码有什么问题,如果您仍然找到解决方案,那么这里有一个很小的更改,我已经made.. (stackblitz)

© www.soinside.com 2019 - 2024. All rights reserved.