在ng-bootstrap中,我无法将function
分配给属性[ngbTypeahead]。在Typeahead的示例代码中,箭头表达式(lambda表达式)用于构造委托人search
。
[...]
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => this.searching = true),
switchMap(term =>
this._service.search(term).pipe(
tap(() => this.searchFailed = false),
catchError(() => {
this.searchFailed = true;
return of([]);
}))
),
tap(() => this.searching = false)
);
[...]
当我更改了初始化搜索的方式时,出现了undefined
值this
的错误。这是我的实验代码。
// this code is working fine.
[...]
costCenterFromSearch = (text$: Observable<string>) => {
return text$.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term => {
return this.http.get(this.typeAheadUrl, {
params: new HttpParams().set("search", term)
}).pipe(
map(response => {
return _.map(response, f => (<any>f).Key);
}))
}
)
);
};
[...]
// this code is raising errors.
[...]
costCenterFromSearch = function (text$: Observable<string>) {
return text$.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term => {
return this.http.get(this.typeAheadUrl, {
params: new HttpParams().set("search", term)
}).pipe(
map(response => {
return _.map(response, f => (<any>f).Key);
}))
}
)
);
};
[...]
但是,当我将此示例代码放入TypeScript Playground
时class foo {
a: string = "testing";
constructor() {}
bar_func = function () {
console.log(this.a);
}
bar_lambda = () => {
console.log(this.a);
}
}
从Playground结果中,this
在函数表达式和箭头表达式中均可用。因此,我很困惑this
在箭头表达式中是否可用,因为它在ngbTypeahead属性中不起作用。