在我的 Angular ionic 项目中,当我登录第一页时出现错误“错误错误:未捕获(承诺):类型错误:无法读取 null 的属性‘订阅’”但是当我重新加载页面时我不没有错误,我有数据。谢谢
(await this.pageService.getAllTables()).subscribe((res: any) => {
this.tables = res.body
});
}```
```getAllTables() {
this.storage.get('USER').then(user =>{this.user = user;});
return this.storage.get('ACCESS_TOKEN').then(token =>{
if (this.user) {
return this.http.get(this.url + 'table/' + this.user.id, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}),
observe: 'response'
});
}
return null;
});
}```
答案 0 :(得分:0)
试试这个
getAllTables() {
return this.storage.get('USER')
.then(user =>{this.user = user;})
.then(() => this.storage.get('ACCESS_TOKEN'))
.then(token =>{
if (this.user) {
return this.http.get(this.url + 'table/' + this.user.id, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}),
observe: 'response'
});
}
return null;
});
这段代码仍然很奇怪,因为你返回了 observable,包裹在 promise 中,但至少应该可以工作。
您可以尝试将所有内容转换为承诺。它看起来像这样:
getAllTables() {
return this.storage.get('USER')
.then(user =>{this.user = user;})
.then(() => this.storage.get('ACCESS_TOKEN'))
.then(token =>{
if (this.user) {
return this.http.get(this.url + 'table/' + this.user.id, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}),
observe: 'response'
}).toPromise();
}
return null;
});
用法:
this.tables = (await this.pageService.getAllTables())?.body;
答案 1 :(得分:0)
我认为您订阅时您的 this.pageService.getAllTables 尚未加载。
请先在构造函数中注入“pageService”,然后将所有内容转换为promise
喜欢这个
constructor(){
private pageService: PageService
}
之后将所有内容转换为承诺
getAllTables() {
return this.storage.get('USER')
.then(user =>{this.user = user;})
.then(() => this.storage.get('ACCESS_TOKEN'))
.then(token =>{
if (this.user) {
return this.http.get(this.url + 'table/' + this.user.id, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}),
observe: 'response'
}).toPromise();
}
return null;
});