angular2组件传值

https://img3.mukewang.com/5bd5679600016ee005480408.jpghttps://img.mukewang.com/5bd5679e00011d4c05590309.jpg

上面是我的页面的入口代码,top是顶部logo显示部分,slider是我的左侧菜单,main中是我具体的页面。

我的页面是管理系统类型的,所以当为login路径时,我希望左侧的slider是不显示的(isLogon为false),那么假如我在login页面登录成功了,我如何使登录成功的状态传递给页面入口的isLogon属性值为true,使slider显示?


浮云间
浏览 654回答 1
1回答

不负相思意

假设你有一个login serviceimport { Injector, Injectable } from '@angular/core';import { Router } from '@angular/router';import { Subject } from 'rxjs';@Injectable()export class LoginService{&nbsp; &nbsp; public isLogined: boolean;&nbsp; &nbsp; private changes: Subject<any> = new Subject<any>();&nbsp; &nbsp; constructor() {&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; isLogined(isLogined: boolean): void {&nbsp; &nbsp; &nbsp; &nbsp; this.isLogined = isLogined;&nbsp; &nbsp; &nbsp; &nbsp; this.changes.next(this.isLogined);&nbsp; &nbsp; }}然后在你的页面中import { Component, Input, Output, EventEmitter, OnInit, OnChanges, OnDestroy } from '@angular/core';import { Router } from '@angular/router';import { LoginService } from './login.service';@Component({&nbsp; &nbsp; selector: 'myApp',&nbsp; &nbsp; template: `&nbsp; &nbsp; &nbsp;<slider *ngIf="this._loginService.isLogined"></slider>`})export class myApp {&nbsp; &nbsp; constructor(private _loginService: LoginService) {&nbsp; &nbsp; }}将slider的 *ngIf绑定的 loginservice.isLogined 属性。然后你就可以在登陆成功处,设置 _loginService.isLogined(true);这样每次当你login成功后,状态就会通知到slider啦。这里主要用到RxJS的Subject.有什么问题可以继续提问。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript