首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >此关键字的角6作用域在子组件中是不同的。

此关键字的角6作用域在子组件中是不同的。
EN

Stack Overflow用户
提问于 2018-12-04 14:31:09
回答 1查看 385关注 0票数 4

我有一个组件,我们可以称之为Profile-Main。Profile-Main具有以下数据检索功能:

代码语言:javascript
复制
getData(text: string): Observable<Response> {
    const baseUrl = environment.apiURL + "Profile/";
    const params = new HttpParams().set('userName', text);

    return this.httpClient
           .get(baseUrl + 'GetUser', {params: params})
           .map(response => <Response>response);
}

现在,配置文件-主组件使用了角输入标签组件(ngx-芯片).我正在尝试实现自动完成功能,它将一个ref传递给getData函数,如下所示:

代码语言:javascript
复制
<div class="col-sm-10">
    <tag-input class="tag-chips" [secondaryPlaceholder]="'Enter your User Name'"
                name="userName" [ngModel]="['Test User']" [maxItems]="1" [ripple]="false"
                [onlyFromAutocomplete]="true">

    <tag-input-dropdown [appendToBody]="false" [displayBy]="'Name'" [identifyBy]="'id'"
                  [autocompleteObservable]="getData">
    </tag-input-dropdown>
    </tag-input>
</div>

现在的问题是,当getData方法被击中时,this.httpClient是未定义的,因为此时this关键字的作用域指的是TagInputDropdownComponent而不是ProfileMainComponent

我该如何解决这个问题?我在网上看到输入参数上有很多源,但问题是我不能直接编辑npm包?

我刚接触到第六角,但必须有一个简单的方法来解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-04 14:39:27

如果允许编辑具有getData函数的组件,请尝试使用Arrow函数语法,它将自动绑定this

代码语言:javascript
复制
getData = (text) : Observable<Response> =>  {
    const baseUrl = environment.apiURL + "Profile/";
    const params = new HttpParams().set('userName', text);

    return this.httpClient
      .get(baseUrl + 'GetUser', {params: params})
      .map(response => <Response>response);
  }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53615184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档