如何让Angular中的其他组件可以访问变量?

时间:2017-05-23 16:53:05

标签: 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-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}}。但是,即使我不使用它,这个父级的子组件也会产生错误,

"ERROR TypeError: Cannot read property 'name' of undefined"

我猜我需要在我的子组件中引用用户变量

2 个答案:

答案 0 :(得分:1)

在文档HERE

中有完整的内容

但实际上有三种组件通信方法。 @Input/@Output @ViewChild 服务

<强> @Input/@Output

这对于快速关联的更改很常见,特别是对于ngFor

这样的更改
<div>
    <childComp *ngFor="let item of items" [item]="item" (specialEvent)="doSomething()"></childComp>
</div>

这可以让你传递&#34;项目&#34;对于孩子,在孩子内部,你可以发出&#34; specialEvent&#34;父母会听。我有这些组件,这些组件由于显示原因而复杂,但没有大量逻辑,所以他们将它们发送给父母。

如果你打算超过一个或两个等级,我就不会使用这种方法。

<强> @ViewChild

@ViewChild()允许您实际使用子组件的公共方法或更改其变量。它比@Input更深入,但如果我诚实,我从不使用它。当我需要一个子元素并想要产生效果或从DOM对象获取值时,我几乎只使用它。

<div id="moverWrapper" #moverWrap>
    <div class="mover" [ngStyle]="moverStyle()"></div>
</div>

@ViewChild(moverWrap) moverWrap: ElementRef;
let width = this.moverWrap.nativeElement.offsetWidth; 

服务 虽然服务确实是你想做的最好的方式,但我不会通过例子,因为我发送的链接更好。但是,如果您想要全局(例如用户),那么您需要将其保留在服务中并将其注入您需要的位置。我在95%的时间使用此方法。

希望有所帮助!

答案 1 :(得分:0)