Tuesday, 23 May 2017

How do you let variables accessible to other components in angular 2?

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'])
  }
}

The above component is basically nav component, and I have a lot of other components inside of this component. I was wondering how to access the user variable for components inside of this component?



via Eric Chu

No comments:

Post a Comment