我经常遇到这个问题。尝试获取用户列表(从数据库中)并将其显示在
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'。
我只能假定user-admin.component userNames具有相同的列表。 (我测试了html以确保它会在列表中列出名称)。
解决方案?我以为我必须强制执行ChangeDetection,这似乎确实没有必要吗?
或this.userNames必须是一个引用变量。我以为已经(字符串类型列表)。我尝试创建仅具有this.userName作为唯一内容的类,然后传递了一个“新的AllUsers”类,但是AllUsers内部的列表也没有显示用户名。
想法?提前致谢。瑜伽士。
您是否尝试过异步管道
您不需要订阅服务,而是订阅insde组件类。这样,您无需强制进行更改检测。更新userNames(组件类属性)后,它将自动呈现。
您需要在服务中返回从HTTP请求返回的可观察对象,并为其订阅组件。尝试以下]]
user-admin.component.ts