Angular:从异步获取数据;我不必强制更改检测

问题描述 投票:0回答:3

我经常遇到这个问题。尝试获取用户列表(从数据库中)并将其显示在

user-admin.component.html:

<div class="col-md-2 offset-1">
    <select size=20 [ngStyle]="{'width': '200px'}"> 
      <option *ngFor="let name of userNames">{{name}}</option>
    </select>
</div>

user-admin.component.ts

  userNames: string[] = [];

  constructor(private fb: FormBuilder,
              private authService: AuthService
              ) { }

  ngOnInit() {
    this.authService.getAllUserNames(this.userNames);

getAllUserNames是服务中的函数:authService。

  getAllUserNames(userNames: string[]) {
    this.http.get(this.baseUrl + 'usernames').subscribe( (results: string[]) => {
      userNames = results;
    });
  }

当页面启动(ngOnInit)并调用此函数时,它将正确返回带有两个用户名列表的'userNames'。enter image description here

我只能假定user-admin.component userNames具有相同的列表。 (我测试了html以确保它会在列表中列出名称)。

解决方案?我以为我必须强制执行ChangeDetection,这似乎确实没有必要吗?

或this.userNames必须是一个引用变量。我以为已经(字符串类型列表)。我尝试创建仅具有this.userName作为唯一内容的类,然后传递了一个“新的AllUsers”类,但是AllUsers内部的列表也没有显示用户名。

想法?提前致谢。瑜伽士。

angular pass-by-reference angular-changedetection
3个回答
0
投票

您是否尝试过异步管道


0
投票

您不需要订阅服务,而是订阅insde组件类。这样,您无需强制进行更改检测。更新userNames(组件类属性)后,它将自动呈现。


0
投票

您需要在服务中返回从HTTP请求返回的可观察对象,并为其订阅组件。尝试以下]]

user-admin.component.ts

© www.soinside.com 2019 - 2024. All rights reserved.