Observable未填充变量



我的observable正在传递回正确的对象,但数据不是针对本地变量存储的。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { LookupListsService } from '../../services/lookup-lists.service';
import { SexList } from '../../models/lookups/sexType';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit, OnDestroy {
sexLists: SexList[] = [];
constructor(private lookupService: LookupListsService) { }
ngOnInit(): void {
this.getGenderList();
this.getCountryList();
this.getSexList(); 
const body = document.getElementsByTagName('body')[0];
body.classList.add('register-page');
body.classList.add('off-canvas-sidebar');
}
ngOnDestroy(): void {
const body = document.getElementsByTagName('body')[0];
body.classList.remove('register-page');
body.classList.remove('off-canvas-sidebar');
}
getSexList(): void {
this.lookupService.getSexList()
.subscribe(sexlist => {
console.log(sexlist)
this.sexLists = sexlist
});
}
}

我可以在开发者工具中看到这个对象:

{
"sexList": [
{
"sexId": 1,
"sexCode": 1,
"sexText": "Male"
},
{
"sexId": 2,
"sexCode": 2,
"sexText": "Female"
}
]
}

但在我的布局上,我有以下内容:

<div><p>There are: {{sexLists.length}} records in the list</p></div>

我在控制台中得到了一个未定义的sexLists,我在页面上返回的文本是:

列表中有:条记录

我不明白为什么这个物体永远不会固定下来。

编辑添加的服务代码:

getSexList(): Observable<SexList[]> {
var apiURL = this.api.getApiEndPointByName('GetSex');
console.log(apiURL);
var sex = this.http.get<SexList[]>(apiURL);
return sex;
}

您将一个带有数组的对象分配给组件,而不是数组-我建议"拔除";响应中的数组,例如:

getSexList(): void {
this.lookupService.getSexList()
.pipe(pluck('sexList'))
.subscribe(sexlist => {
console.log(sexlist)
this.sexLists = sexlist
});
}

(您需要从RxJs导入pluck-运算符(

最新更新