Angular 如何让其他组件可以访问角度中的变量?
Dashboard.component.tsAngular 如何让其他组件可以访问角度中的变量?,angular,Angular,Dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../auth/auth.service'; import { User } from '../auth/user.model' @Component ({ selector: "app-dashboa
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth/auth.service';
import { User } from '../auth/user.model'
@Component ({
selector: "app-dashboard",
templateUrl: "./dashboard.component.html",
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
user: User;
constructor (private authService: AuthService, private router: Router) {}
ngOnInit() {
this.authService.getUser()
.subscribe(
(user: User) => {
this.user = user;
}
)
}
onLogout() {
this.authService.logout();
this.router.navigate(['/login'])
}
}
上面的组件基本上是导航组件,我在这个组件中还有很多其他组件。我想知道如何访问该组件内部组件的用户变量
编辑:我需要重新措辞这个问题。我提出上述问题的原因是:
我在父组件中显示用户属性,如{{user.name}。但此父级的子级组件会产生错误,即使我不使用它
“错误类型错误:无法读取未定义的属性‘名称’”
我猜我需要在我的子组件中引用用户变量您可以用下一种方法执行此任务:
文档中对此有完整的描述 但实际上有3种方法可以实现组件通信。
@Input/@Output
,@ViewChild
,以及服务
@Input/@Output
:
这对于快速链接的更改很常见,尤其是对于ngFor
<div>
<childComp *ngFor="let item of items" [item]="item" (specialEvent)="doSomething()"></childComp>
</div>
服务
作为一个服务确实是最好的方式来做你想要的,虽然,我不会通过例子,因为我发送的链接有更好的。但是有了一个您想要的全局值(就像用户一样),您就可以将其保留在服务中,并将其注入到您需要的地方。。我95%的时间都用这种方法
希望有帮助 “用户变量”是指“属性”吗?通常,访问子组件属性是一种不好的做法,反映了程序设计的糟糕。
。然后@Input()用户代码>在您的孩子中。
<div id="moverWrapper" #moverWrap>
<div class="mover" [ngStyle]="moverStyle()"></div>
</div>
@ViewChild(moverWrap) moverWrap: ElementRef;
let width = this.moverWrap.nativeElement.offsetWidth;