如何在登录成功后获取页眉和页脚

时间:2017-10-22 15:21:53

标签: angular

在我的应用程序组件中,我有标题页脚指令,并且我之间有路由器插座来呈现所有其他组件。

App.Component.html:

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

App.Component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    title = 'Smart Shopping';

}

最初我在应用程序启动时渲染我的登录组件。

Login.Component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../shared/services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
  credentials = { username: '', password: '' };

  constructor(
    private router: Router,
    private service: AuthService
  ) { }

  ngOnInit() {
  }

  login() {
    this.service.login(this.credentials.username, this.credentials.password)
      .subscribe(
        data => {
          console.log(data);
          this.router.navigate(['home']);
        },
        err => {
          console.log(err);
        }
      )

  }
}
登录按钮上的

我将加载主页组件

在这一步,我希望我的页眉和页脚可见。我希望用户只有在登录后才能看到页眉和页脚。

我可以通过在Home组件中给出页眉和页脚的指令来做到这一点,但是通过这样做,我必须在所有其他组件中给出指令以获取页眉和页脚,这不是一个好的方法。我的欲望如何输出?

2 个答案:

答案 0 :(得分:0)

您也可以将* ngIf与页脚和标题一起使用

<app-header *ngIf="loggedIn"></app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="loggedIn"></app-footer>

然后将loggedIn属性添加到类

export class LoginComponent implements OnInit {
  credentials = { username: '', password: '' };
  loggedIn = false;
  constructor(
    private router: Router,
    private service: AuthService
  ) { }

  ngOnInit() {
  }

  login() {
    this.service.login(this.credentials.username, this.credentials.password)
      .subscribe(
        data => {
          this.loggedIn = true;
          console.log(data);
          this.router.navigate(['home']);
        },
        err => {
          this.loggedIn = false;
          console.log(err);
        }
      )

  }
}

答案 1 :(得分:-1)

你可以这样使用 例如,创建一个包装器组件 的 wrappercomponent

 <app-header></app-header>
<ng-content></ng-content>
<app-footer></app-footer>

以及您希望页眉和页脚可见的位置,例如,如果您想要在主组件中,那么在主组件的html中使用包装指令,如

<wrapper>
home component here
</wrapper>