如何在登录后调用构造函数和ngOnInit

时间:2018-04-28 15:05:34

标签: angular5 jhipster

我为HomeComponent定义一个路由'',在组件的html页面中有一个登录链接,在login()之后,url没有改变,并且没有调用构造函数和ngOnInit,所以{{currentSubject?。 name}}为空,如果我按F5刷新页面,将调用ngOnInit,并在页面中显示{{currentSubject?.name}}。

我的问题是:如何在登录后调用ngOnInit使页面中显示currentSubject.name?:

html页面如下:

<div [ngSwitch]="isAuthenticated()">
	<div *ngSwitchCase="false" class="row">
		<div class="col-md-3">
			<span class="hipster img-fluid rounded"></span>
		</div>
	<div class="col-md-9">
			<div class="alert alert-warning">
				<span>existing account, please </span>
				<Button class="btn btn-primary" (click)="login()" jhiTranslate="global.messages.info.authenticated.link">login</Button>
			</div>
		</div>
	</div>
	<div *ngSwitchCase="true">
		<nav class="navbar navbar-expand-lg navbar-light bg-light">
			<div class="collapse navbar-collapse" id="navbarSupportedContent">
				<ul class="navbar-nav mr-auto">
					<li ngbDropdown class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" ngbDropdownToggle href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							{{currentSubject?.name}}
						</a>
						<div *ngIf="currentSubject" ngbDropdownMenu class="dropdown-menu" aria-labelledby="navbarDropdown">
							<a class="dropdown-item" *ngFor="let subject of subjects" href="#">{{subject.name}}</a>
						</div>
					</li>
				</ul>
				<ul class="navbar-nav">
					<li class="nav-item">
						<a class="nav-link" href="#">Link 1#</a>
					</li>
					<li class="nav-item">
						<a class="nav-link" href="#">Link 2#</a>
					</li>
				</ul>
			</div>
		</nav>
	</div>
</div>

ngOnInit()如下:

    ngOnInit() {
        this.principal.identity().then((account) => {
            this.account = account;
        });
        this.registerAuthenticationSuccess();

        this.profileService.getProfileInfo().then((profileInfo) => {
            this.swaggerEnabled = profileInfo.swaggerEnabled;
        });

        this.subjectService.query({
            page: 0,
            size: this.itemsPerPage,
            sort: ['id', 'asc']
        }).subscribe(
            (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
            (res: ResponseWrapper) => this.onError(res.json)
        );
    }

subects和currentSubject将填充在onSuccess函数中,我将跳过此处。

1 个答案:

答案 0 :(得分:0)

不是在ngOnInit中定义currentSubject.name,而是通过订阅可以使用eventManager完成的成功身份验证事件来完成

this.eventManager.subscribe('authenticationSuccess', (data) => {*code here*});