Angular http服务清除RequestOptions搜索参数

时间:2017-05-29 19:32:45

标签: angular

如果未定义值,我不需要传入URL中的任何查询参数。在AngularJS中,当某种参数被传递到$resource服务并且其值为空或未定义时,它从未被附加到URL字符串,但是在Angular中,Http服务连同其RequestOptions对象一起用于set headers和parameters的行为方式不同。

例如这个输入元素:

<select class="form-control form-control-sm" formControlName="catalogCode" title="Catalog Code">
    <option value="">- Catalog Code -</option>
    <option *ngFor="let option of codes" [value]="option.code">
      {{ option.text }}
    </option>
  </select>

这会更新我已定义的QueryParameters,并在服务中使用,如下所示:

getOfferings(parameters: QueryParameters): Observable<Offering[]> {
    let requestOptions = new RequestOptions({
      search: {
        catalogCode: parameters.catalogCode
      }
    });

    return this.http.get(`${environment.BASE_URL}/offerings`, requestOptions)
      .map(response => response.json());
  };

如果填充了parameters.catalogCode,则查询运行正常并且URL看起来正确:http://localhost:4200/offerings?catalogCode=CODE1,但是当我从列表中选择空选项时,URL将为?catalogCode=为空值。

不幸的是,我的后端不喜欢空catalogCode所以我真的想要阻止它,因为它曾经是旧的Angular。有没有正确的方法来清除它?

2 个答案:

答案 0 :(得分:1)

你必须自己做。这很好,因为你可以选择你需要的确切行为,而不是建立在外部库隐藏的固定的假性行为上。

在lodash中执行此操作的一些方法:

const search = {
  catalogCode: parameters.catalogCode
};

const requestOptions = new RequestOptions({
  // only remove undefined, my preferred option
  search: _.omitBy(search, _.isUndefined)
});

  // remove undefined and null (but not empty strings or the number 0)
  search: _.omitBy(search, _.isNil)

  // remove undefined, null, and empty string (but still not the number 0)
  search: _.omitBy(search, x => _.isNil(x) || x === '')

答案 1 :(得分:0)

我认为除了手动过滤价值之外还有其他方法。

PLUNKER

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule, ReactiveFormsModule, FormBuilder} from '@angular/forms';
import {HttpModule, Http, URLSearchParams} from '@angular/http';

@Component({
  selector: 'my-app',
  template: `
<form [formGroup]="myFormGroup" (ngSubmit)="onSubmit()">
  <select class="form-control form-control-sm" formControlName="catalogCode" title="Catalog Code">
    <option value="">- Catalog Code -</option>
    <option *ngFor="let option of codes" [value]="option.code">
      {{ option.text }}
    </option>
  </select>

  <button type="submit">Submit</button>
</form>
  `,
})
export class App {

  public myFormGroup;

  public codes = [
    { code: 'option1', text: 'option 1' },
    { code: 'option2', text: 'option 2' },
    { code: 'option3', text: 'option 3' },
  ];

  constructor(private formBuilder: FormBuilder, private http: Http) {
    this.myFormGroup = formBuilder.group({
      catalogCode: ['']
    });
  }

  public onSubmit() {
    const formValue = this.myFormGroup.value;
    const params = new URLSearchParams();

    Object.keys(formValue).forEach(key => {
      const value = formValue[key];
      if(value === null || value === undefined || value === '') {
        return;
      }

      params.set(key, value); 
    });

    const url = `http://localhost:8888/test?${params.toString()}`;

    alert(url);

    this.http.get(url);
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}