从其他组件Angular + NativeSript
调用函数时,视图不会更新。我正在调用一个函数来获取一些数据并进行渲染,但是该数据未显示在组件中,但是在console log
中,我可以看到数据在那里。
我在这里想念什么?
我的Tabcomponent
在这里从其他component
处调用该函数:
@Component({
providers: [CartoesComponent],
selector: "ns-tabs",
templateUrl: "./tabs.component.html",
styleUrls: ["./tabs.component.css"],
moduleId: module.id
})
export class TabsComponent implements OnInit {
tabSelectedIndex: number;
constructor(private card: CartoesComponent) {
this.tabSelectedIndex = 0;
}
onSelectedIndexChanged(args: SelectedIndexChangedEventData) {
if (args.oldIndex !== -1) {
const newIndex = args.newIndex;
if (newIndex === 0) {
// the function im calling
this.card.getCards();
}
}
}
}
我要调用的函数所在的组件:
@Component({
selector: "Cartoes",
moduleId: module.id,
templateUrl: "./cartoes.component.html",
styleUrls: ["./cartoes.css"]
})
export class CartoesComponent implements OnInit {
processing = false;
cardsData: any = null;
cardsDetails: any = null;
constructor() {}
getCards(): void {
this.processing = true;
this.service.cardsWallet().subscribe((res) => {
this.cardsData = res;
this.cardsData.forEach((data: any) => {
this.cardsDetails = data.cards;
});
// DISMISS LOADER
this.processing = false;
}, (err) => {
this.processing = false;
console.log(err);
});
}
}
我的视图组件xml(html)。 我的视图保持空白,但是在console.log中我可以看到数据。 如果在ngOnInit上调用该函数,它将显示视图,但再次调用该函数则不会更新。
<Carousel debug="false" height="200" width="100%" indicatorOffset="0, 0" indicatorColor="#00E676" finite="true" bounce="true" showIndicator="true" verticalAlignment="top" android:indicatorAnimation="SCALE" indicatorColorUnselected="#000" [items]="cardsDetails">
<CarouselItem verticalAlignment="middle" *ngFor="let card of cardsDetails">
<AbsoluteLayout width="auto">
<!-- CARD IMG -->
<Image src="~/images/cartoes/card4.png" width="325" class="card-img"></Image>
<Image *ngIf="card?.cardBrand.cardBrandName === 'Mastercard'" src="~/images/cartoes/mastercard.png" width="50" class="card-img-detail"></Image>
<Image *ngIf="card?.cardBrand.cardBrandName === 'Visa'" src="~/images/cartoes/visa.png" width="50" class="card-img-detail"></Image>
<!-- CARD INFO -->
<label text="{{card?.cardDescription}}" class="card-info-description"></label>
<label text="{{card?.cardNumber}}" class="card-info-number"></label>
<label text="{{card?.expirityDate | date:'MM/yy'}}" class="card-info-validade" textWrap="true"></label>
<label text="{{card?.cardHolderName}}" class="card-info-nome" textWrap="true"></label>
</AbsoluteLayout>
</CarouselItem>
</Carousel>
答案 0 :(得分:1)
实际上,您已经注入了组件并将其声明为提供程序。
constructor(private card: CartoesComponent) {
this.tabSelectedIndex = 0;
}
这意味着Angular创建了此组件类的实例,您可以调用其方法。
但是,该实例并未引用任何真正呈现的组件,并且未绑定到视图中的任何模板。因此,在您的情况下,调用组件实例方法应该不会有任何影响。
正确的方法应该是通过ViewChild装饰器引用该组件(如果它位于父组件内部)。在这种情况下,您将使用完全渲染的组件并影响其模板。否则,您应该使用某些服务在组件之间进行通信或共享公用数据。 Here您可以找到有关组件通信的全面说明。
到目前为止,我唯一不知道为什么调用ngOnInit
会处理情况,因为它不应该处理。一旦确定情况后,我将更新答案。