API数据在组件中使用时未定义



我有这个服务从API获取数据,并保存到数组之后:

export class DataService {
constructor(private http: HttpClient) { }
readonly baseURL = "https://localhost:44302/api";
books: Book[];
users: User[];
cards: Card[];
postId: number;
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
getBooks() {
return this.http.get(this.baseURL + '/books');
}
getCards() {
return this.http.get(this.baseURL + '/cards');
}
getUsers() {
return this.http.get(this.baseURL + '/users');
} 
getData() {
const observableList: Observable<any>[] = [];
observableList.push(this.getBooks());
observableList.push(this.getUsers());
observableList.push(this.getCards());
forkJoin(observableList).subscribe(resultList => {
this.books = resultList[0] as Book[];
this.users = resultList[1] as User[];
this.cards = resultList[2] as Card[];
});
}

在我的组件中,我运行getData方法并尝试console.log数据,但它一直说数据是未定义的,即使api数据显示在调试网络选项卡中:

export class MainComponent implements OnInit {
books: Book[];
users: User[];
cards: Card[];
selectedBook: Book;
display: boolean = false;
selectedUser: User;
constructor(public dataService: DataService) { }
ngOnInit() {
this.dataService.getData();
//Save data in local component arrays
this.books = this.dataService.books;
this.users = this.dataService.users;
this.cards = this.dataService.cards;
console.log(this.books); // ==> "undefined"
}

组件内分配的数组(在服务调用之后)将在getData()服务完成订阅三个可观察对象之前执行。这就是为什么要给未定义的数据赋值。

在你的服务中,修改它以只返回可观察对象:

getData() {
const observableList: Observable<any>[] = [];
observableList.push(this.getBooks());
observableList.push(this.getUsers());
observableList.push(this.getCards());
return forkJoin(observableList);
}

在您的组件中,然后在订阅者:

中调用getDate()订阅已连接的数据:
this.dataService.getData()
.subscribe(({resultOne, resultTwo, resultThree}) => {
//Save data in local component arrays
this.books = resultOne;
this.users = resultTwo;
this.cards = resultThree;
});
}

最新更新