【问题标题】:How to Call api on Keypress in Angular如何在 Angular 中的 Keypress 上调用 api
【发布时间】:2021-09-02 02:32:56
【问题描述】:

当用户在文本框上单击(在按键事件上)时,我试图触发 API 调用,我该怎么做 Angular。我在使用 debounce 方法时遇到错误 Cannot read property 'valueChanges' of undefined

app.component.ts

ngOnInit() {

    this.searchField.valueChanges

        .pipe(
            debounceTime(500),
            distinctUntilChanged(),
            map((val) => {
                this.http.post<any>('http://localhost:3000/articles/articleslistData', { pubid: '3', pubdate: this.dateChanged }).subscribe({
                    next: data => {
                        console.log(data);
                    },
                    error: error => {
                        this.errorMessage = error.message;
                        console.error('There was an error!', error);
                    }
                })
            })
        )
        .subscribe();
}

app.component.html

<div class="form-field col-lg-12">
<label class="label" for="message">Headline</label>
<input id="message" class="input-text js-input" type="text" required [formControl]="searchField">
</div> 

【问题讨论】:

  • 您在哪里以及如何初始化您的 this.searchField ?看来你的属性没有初始化
  • @federicoscamuzzi 请注意你的舌头兄弟
  • @Lautre 我在构造函数 searchField: FormControl; 之前初始化我的 this.searchField

标签: angular typescript rxjs


【解决方案1】:

此外,你需要使用 switchMap (switchMap "reemplace" one observable by another one) 类似

this.searchField.valueChanges.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    switchMap ((val) => {
          //we can not return the "val", else
          //the result of this.http.post
          // here you has "val", I suppose i your call
          // you use it
        return this.http.post<any>('http://localhost:3000/articles/articleslistData', { pubid: '3', pubdate: this.dateChanged })
    })
).subscribe(data => {
   console.log(data);
},
error => {
  this.errorMessage = error.message;
  console.error('There was an error!', error);
}
);

看到您只有一个订阅

【讨论】:

    【解决方案2】:

    您需要在 ngOnInit 或属性声明中初始化表单控件。

    export class MyClass {
      // solution 1
      public searchField = new FormControl({});
      ngOnInit() {
          // solution 2
          this.searchField = new FormControl({});
          // your code here
      }
    }
    

    您也可以使用 FormBuild 类 欲了解更多信息

    见:https://angular.io/api/forms/FormControl#initializing-form-controls

    【讨论】:

    • 是的,它可以工作,但在我的文本框字段中它只显示[object object],虽然我的api只包含2个值ArticleIDTitle
    • 这取决于您想做什么,在您的问题中,我没有看到设置字段值有任何薄弱之处。但是输入应该只包含原始数据,如stringnumber 等......如果你有[object object],这意味着你将完整的对象{ArticleID: any; Title: any} 作为输入值。
    • 它没有工作仍然得到[object object]你有时间请帮忙!
    • 你能创建一个带有可重现错误的堆栈闪电战
    猜你喜欢
    • 2019-03-04
    • 2017-12-22
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多