在TypeScript中,通过函数表达式和箭头表达式初始化的变量中是否可以使用“ this”?

时间:2018-07-30 05:53:14

标签: javascript angular typescript ng-bootstrap

在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)
);
[...]

当我更改了初始化搜索的方式时,出现了undefinedthis的错误。这是我的实验代码。

// 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);
            }))
        }
        )
    );
};
[...]

Picture1

// 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);
            }))
        }
        )
    );
};
[...]

Picture2

但是,当我将此示例代码放入TypeScript Playground

Picture3

class foo {
    a: string = "testing";
    constructor() {}

    bar_func = function () {
        console.log(this.a);
    }

    bar_lambda = () => {
        console.log(this.a);
    }
}

Picture4 从Playground结果中,this在函数表达式和箭头表达式中均可用。因此,我很困惑this在箭头表达式中是否可用,因为它在ngbTypeahead属性中不起作用。

0 个答案:

没有答案