我有一个应用程序,其中app(main).component.html。
中有一个下拉列表 <li class="dropdown" *ngIf="sessionService.isLoggedIn || sessionService.isFirstTimeLogin">
<a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span class="hidden-md">Select Company</span>
</a>
<ul class="dropdown-menu">
<li *ngFor="let company of companyList">
<a (click)="selectCompany(company)">{{company.CompanyName}}</a>
</li>
<!--<li><a><i class="dropdown-icon fa fa-envelope"></i> Messages</a></li>-->
</ul>
</li>
循环用于向select中的选项添加数据的变量companyList
是从app.component.ts中的服务获取数据。
getCompanyList() {
//this.loaderService.showLoader();
this.masterService.getCompanyList()
.subscribe(
(response) => {
this.companyList = response.data.recordset;
this.loaderService.hideLoader();
},
(error) => {
this.loaderService.hideLoader();
})
}
正在调用ngOnInit。
ngOnInit() {
if (localStorage.getItem("isLoggedIn")){
this.getCompanyList();
}
}
问题是登录后仪表板页面打开但是下拉列表在app.component.html中。因此,数据不会首先在组件加载时填充,但是当我刷新页面时,下拉列表会填充
答案 0 :(得分:0)
你在ngOnInit
上调用该函数。该函数订阅了observable并返回
调用一个订阅的函数将无效,因为订阅位于函数的堆栈而不是**组件的内存
答案 1 :(得分:0)
试试这个,当子组件加载时,它将执行ngOnInit()
,这将触发父组件的事件并执行父组件的next()
。
子组件
@Output() callparent = new EventEmitter < string > ();
ngOnInit() {
this.callparent.emit('some data');
}
父组件HTML
<div class="centered-content">
<child-component (callparent)="next($event)"></child-component >
</div>
父组件
next(event) {
console.log('Hi From parent');
}
答案 2 :(得分:0)
这不是模板问题或加载顺序,相反,没有人现在正在为角色免费观看此变量companyList
。
解决问题的方法很多,
<强>服务即可。通过observable
,如果login
是服务,您可以发布observable
,例如。 $companies
,以便使用此服务的任何人都可以订阅它。这样你的显示逻辑可以在其他地方。教程:https://angular-2-training-book.rangle.io/handout/observables/using_observables.html
this.login.$companies.subscribe(userList => ...);
<强>组件即可。确保companyList
是显示在显示组件中的@Input()
变量,例如。 companyListComponent
。当companyList
引用被修改时,Angular会为您监视它。然后,您可以通过<company-list [items]="companyList" />
export class companyListComponent {
@Input() items;
}
无论哪种方式,我们的想法是你需要首先从你的逻辑中制作一个可重用的东西,这在这里恰好是件好事。