我有一个模板,其中链接根据'userId'变量而变化。
<nav>
<div class="nav-wrapper">
<a href="#" class="brand-logo"><img src="../../public/images/logo.png" alt="" /></a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>
<a routerLink="" routerLinkActive="active"></a>
</li>
<li *ngIf="userId"><a>Welcome {{userInfo.name}}</a></li>
<li><a routerLink="gallery" routerLinkActive="active">Gallery</a></li>
<li *ngIf="userId"><a routerLink="upload" routerLinkActive="active">Upload</a></li>
<li *ngIf="userId"><a routerLink="logout" routerLinkActive="active">Logout</a></li>
<li *ngIf="! userId"><a routerLink="auth" routerLinkActive="active">Login</a></li>
<li *ngIf="! userId"><a routerLink="auth" routerLinkActive="active">Register</a></li>
</ul>
</div>
</nav>
<router-outlet></router-outlet>
我拥有获取数据服务的组件:
import { Component, OnInit } from '@angular/core';
import { SessionService } from '../session.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [SessionService]
})
export class HomeComponent implements OnInit {
public userId = "";
public userInfo = "";
constructor(
private sessionService: SessionService
) { }
ngOnInit() {
this.userId = this.sessionService.getLoggedInUserId();
if (this.userId !== null) {
this.sessionService.getLoggedInUserDetails(this.userId).subscribe(
data => {
this.userInfo = data.data[0];
}
)
}
}
}
在html部分未检测到服务调用的更改。链接根据'userId'变量显示。
答案 0 :(得分:0)
这可能是由sessionService
引起的,但您的问题并未提供详细信息。
你可以尝试
constructor(
private sessionService: SessionService,
private zone:NgZone
) { }
ngOnInit() {
this.userId = this.sessionService.getLoggedInUserId();
if (this.userId !== null) {
this.sessionService.getLoggedInUserDetails(this.userId).subscribe(
data => {
zone.run() => {
this.userInfo = data.data[0];
});
}
)
}
}
如果这样可以解决问题,那么该服务需要进一步调查。