角度-无法读取未定义的属性

我创建了一个接口httpOption qui contient httpParams,当我想将param设置为httpParam时,出现此错误

无法读取未定义的属性“ params”
export interface HttpOptions {
  headers?: HttpHeaders;
  params?: HttpParams;
  reportProgress?: boolean;
  withCredentials?: boolean;
}

createUsingPOST(args: { createConventionRequest: models.CreateConventionRequest }, requestHttpOptions?: HttpOptions): Observable<string> {
    requestHttpOptions.params.append('responseType', 'text');
}
评论
  • Wolf
    Wolf 回复

    requestHttpOptions is optional, meaning that if it's not here, it'll be undefined.

    When you call your method without a second parameter, you're trying to read property params of undefined, which throws the error.

    You have to give requestHttpOptions a default value if you want it to be optional, like this:

    createUsingPOST(args: { createConventionRequest: models.CreateConventionRequest }, requestHttpOptions: HttpOptions = {}): Observable<string> {
    

    However, it won't fix the issue entirely, as you'll get Cannot read property "append" of undefined.

    因此,您必须决定在不提供第二个参数时想要什么行为。