Angular 如果数组为null,则阻止加载DOM
在组件的html中,我有以下内容:Angular 如果数组为null,则阻止加载DOM,angular,ionic2,Angular,Ionic2,在组件的html中,我有以下内容: <ion-card *ngFor="let recipe of recipeListRef$ | async"> .... <button *ngIf="isExistingFavorite(recipe)"> .... </ion-card> 收藏夹数组加载到构造函数中: favorites: Recipe[]; constructor() { this.favoritesService.getFavorites(
<ion-card *ngFor="let recipe of recipeListRef$ | async">
....
<button *ngIf="isExistingFavorite(recipe)">
....
</ion-card>
收藏夹数组加载到构造函数中:
favorites: Recipe[];
constructor() {
this.favoritesService.getFavorites()
.subscribe(
favorites => {
this.favorites = favorites;
}
);
}
问题是页面在填充“favorites”数组之前加载,这会由于数组为空而导致页面崩溃
我正在寻找一种方法,首先填充数组,然后加载html
~更新~
我已经在组件中添加了以下内容,但是如果用户经过身份验证,它总是拒绝,尽管没有任何console.log打印出来
ionViewCanEnter() {
return new Promise((resolve, reject) => {
if(this.authService.isAuthenticated()) {
this.favoritesService.getFavorites()
.subscribe(
favorites => {
console.log('got the data', favorites);
this.favorites = favorites;
resolve(favorites);
},
error => {
console.log('failed to get data', error);
reject(error);
}
);
}else{
resolve(true);
}
});
下面是getFavorites()服务组件:
favoriteListRef$: FirebaseListObservable<Recipe[]>;
constructor(private database: AngularFireDatabase) {
this.favoriteListRef$ = this.database.list('myUrl', { preserveSnapshot: true});
}
}
getFavorites() {
return this.favoriteListRef$;
}
favoriteListRef$:FirebaseListObservable;
构造函数(专用数据库:AngularFireDatabase){
this.favoriteListRef$=this.database.list('myUrl',{preserveSnapshot:true});
}
}
getFavorites(){
返回此。favoriteListRef$;
}
如果预期要定义的变量在某个点未定义,则该变量应具有初始值:
favorites: Recipe[] = [];
或者,应在预期定义的地方进行额外检查:
isExistingFavorite(recipe: Recipe) {
if (!this.favorites)
return;
for(let f of this.favorites){
...
在Angular中解决此问题的惯用方法是将getFavorites
请求移动到route resolver,这样在实例化route组件时,该数组就可以作为ActivateRoute.snapshot.data['favorites']
使用了
Ionic中路由解析器的替代方案是
对原始角度和离子都有效的方法是为模板提供额外的保护:
<ng-container *ngIf="favorites">
<ion-card ...>...</ion-card>
</ng-container>
...
只需在开始时将其设置为空即可<代码>收藏夹:配方[]=[]@suraj是的,但这只返回一个空数组,这导致isExistingFavorite()方法每次都返回false。我相信IonViewCanCenter就是我要找的。我已将其纳入我的代码中,但有一个问题。请检查我在原始帖子中的编辑。如果它拒绝了,你可以用catch
链接承诺,检查拒绝的内容,然后跟踪它。但是从您发布的代码中,我看不出这里有什么错误。它说favoriteListRef$未定义这听起来很奇怪,因为在您的代码中它是定义的。不管怎样,我想这是件好事。此外,除了使用catch()
之外,还应使用try..catch
捕获承诺构造函数中的错误。
<ng-container *ngIf="favorites">
<ion-card ...>...</ion-card>
</ng-container>