如何在页脚之前加载内容? [英] How can I load the content before the footer?
问题描述
在加载内容之前已加载我的页脚.我的导航栏中有多个按钮,单击这些按钮可以打开一个新组件.当用户点击事件时,事件将从api加载后发出.此时,页脚加载正常.
My footer is getting loaded before the content is loaded. I have multiple buttons in my navbar which when click opens a new component. When the user hits the events, it will emit after the event is loaded from the api. At this time footer is loading fine.
但是在那之后,我转到另一个链接,说特别,然后在事件开始前加载页脚.
But after that I go to another link lets say special then footer is loading before the event.
我尝试如下:
export class EventsComponent implements OnInit {
events = [];
constructor(private _eventService: EventService, private service: SharedService) { }
ngOnInit() {
this._eventService.getEvents()
.subscribe(
res => {
this.events = res,
this.service.footer.emit(),
},
err => console.log(err)
);
}
}
shared.service
import { Injectable, EventEmitter, Output } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
@Output() footer = new EventEmitter<any>();
constructor() {}
}
app.component.ts
export class AppComponent {
flag: boolean;
constructor(private service: SharedService) {
this.service.footer.subscribe(() => {
this.flag = true ;
console.log("Flag is ::: ",this.flag);
})
}
}
app.component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet>
<div class="footer" *ngIf="flag">
<app-footer></app-footer>
</div>
这是一个Stackblitz: https://stackblitz.com/edit/angular-662ndm
Here is a Stackblitz: https://stackblitz.com/edit/angular-662ndm
推荐答案
这是因为您的 ngOnInit 未在更改路线时触发,因此您的代码无法执行.我认为这是已知问题.有一些方法可以显式执行ngOnInit.在下面的线程中进行解释
It's because your ngOnInit is not firing on your route change , So your code won't execute. I think it's known issue. There are some alternative to execute ngOnInit explicitly.It's explain in the below thread
https://github.com/angular/angular/issues/20112
我建议将您的代码移到构造函数中,这样,每次更改路线时构造函数都会调用
I would suggest move your code to the constructor , So constructor will call every time when the route change
constructor(private service: SharedService) {
this.service.footer.emit();
}
订阅后,还可以在应用程序组件上显式调用更改检测,以将模型中的新更改获取到视图中.这是因为subscribe来自RXJS,所以角度不知道该模型是否已更新,因此不会调用更改检测.您可以执行以下调整,以明确地说出模型中发生的更改,然后为我调用更改检测
Also call the change detection explicitly on your app component after subscribe to get the new changes in the model in to the view. It's because subscribe is from RXJS , So angular don't know the model is updated or not , So it won't call change detection. You can do the below tweak to say explicitly to angular something is changes in my model and call the change detection for me
constructor(private service: SharedService,private changeDetector: ChangeDetectorRef) {
this.service.footer.subscribe(() => {
this.flag = true;
this.changeDetector.detectChanges();
console.log("Flag is ::: ", this.flag);
})
}
这是工作样本
https://stackblitz.com/edit/angular-nd1euj-stackoverflow?file=src/app/app.component.ts
这篇关于如何在页脚之前加载内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!