我有一个获取请求,我从服务器获取数据,这就是它的样子
getStreakConfigurations(){
this.loyaltyPointsService.getStreakConfigurations().subscribe( data => {
this.streakConfiguration = data
console.log(this.streakConfiguration,'check')
}
)
}
当我console.log时我明白了
{id: 8, tenantId: null, days: 2, points: 3, tier: 'MID'}
但是当我检查 streakConfid.id 的类型时,它说 undifiend
console.log(typeof this.streakConfiguration.id);
为什么它是未定义的以及为什么它不是一个数字
假设您有一个返回此对象数组的服务 (
mockData
):
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable()
export class LoyaltyPointsService {
constructor() {}
mockData = [
{ id: 1, tenantId: null, days: 2, points: 3, tier: 'MID' },
{ id: 2, tenantId: null, days: 3, points: 5, tier: 'HIGH' },
];
getStreakConfigurations(): Observable<any> {
return of(this.mockData);
}
}
然后您在控制器上使用它,如下所示:
public streakConfiguration: any;
constructor(private loyaltyPointsService: LoyaltyPointsService) {}
ngOnInit() {
this.getConfigurations();
}
getConfigurations() {
this.loyaltyPointsService.getStreakConfigurations().subscribe((data) => {
this.streakConfiguration = data;
// this logs array of objects [{...}, {...}]
console.log(this.streakConfiguration);
// maybe reason why you are seeing undefined when logging id, is because it is array of objects and you cannot access the id by this.streakConfiguration.id
console.log(typeof this.streakConfiguration.id)
// instead you should log like below:
console.log(this.streakConfiguration[0].id);
});
}
}