【发布时间】:2018-03-16 10:18:25
【问题描述】:
MyComponent 使用服务来获取数据,然后呈现该数据。但是,服务无法获取数据,直到用户登录。如果用户第一次访问路由'/myPage',容器组件将显示登录组件。但是,即使呈现登录组件而不是 ng-content(其计算结果为 MyComponent),MyComponent 也会由 angular 初始化并获取并导致服务在登录之前过早获取数据。因此,当用户成功登录和 MyComponent最终渲染,没有数据,初始数据服务什么也没返回。
如何将数据提取推迟到组件渲染之后?我在 MyComponent 中尝试了所有不同的生命周期方法,但均未成功。
app.component
<container>
<router-outlet></router-outlet>
</container>
容器组件
<div *ngIf="!userService.getLoggedInUser()">
<login></login>
</div>
<div *ngIf="userService.getLoggedInUser()">
<ng-content></ng-content>
</div>
路由模块
const routes: Routes = [
{ path: 'myPage', component: myComponent }
];
我的组件
export class MyComponent {
data
constructor(private dataService: DataService) {}
ngOnInit () {
//how can i make run this service AFTER the component renders? i know
//ngOnInit is definitely not the correct lifecycle method, but what is?
this.dataService.get().then((data) => this.data = data);
}
}
【问题讨论】:
-
您正在寻找:angular.io/api/core/AfterViewInit。使用方式与 OnInit 相同(导入,实现,然后使用 ngAfterViewInit () { ... })
-
我认为你走错路了。因为在您的情况下,您需要在任何地方添加您的条件以检查用户是否已登录。这意味着组件已加载,我们可以找到所有 js 文件并进行检查。也许有人可以进行一些 xss 攻击。在 Angular 中,我们有更好的方法来构建守卫。在那里你可以找到一个很好的例子:jasonwatmore.com/post/2016/09/29/…
-
@RomaSkydan 感谢您提供的信息。但我不确定安全问题是什么?是的,客户端检查登录用户,但我也有一个带有令牌的安全检查服务器端(这就是我需要在用户登录后获取数据的原因)。您能否详细说明安全问题出在哪里?
-
@Z.Bagley 不幸的是,当我替换 ngOnInit 时,该生命周期方法不起作用
标签: angular