angular2中的全局数据

问题描述 投票:3回答:1

我正在开发角度2其中我有app组件,它加载其他组件路由器插座,并且还有登录组件的链接。但是我希望能够保存一些全局变量,这个变量可以在我的应用程序组件和登录组件上访问,这样我就可以隐藏并显示登录链接。

这是我的应用程序组件:

import {Component, View, Inject} from 'angular2/core';
import {NgIf} from 'angular2/common';
import {Router, RouteConfig, RouterLink, RouterOutlet, ROUTER_PROVIDERS} from 'angular2/router';


import {HomeComponent} from '../home/home';
import {LoginComponent} from '../login/login';

@Component({
    selector: 'app',
})
@View({
    templateUrl: '/scripts/src/components/app/app.html',
    directives: [RouterLink, RouterOutlet, NgIf]
})
export class App {
    constructor(
        @Inject(Router) router: Router
    ) {
        this.devIsLogin=false;
        router.config([
            { path: '', component: HomeComponent, as: 'Home' },
            { path: '/login', component: LoginComponent, as: 'Login' }
        ]);
    }
}

这是我的logincomponent

///<reference path="../../../node_modules/angular2/typings/node/node.d.ts" />

import {Component, View, Inject} from 'angular2/core';
import {FormBuilder, FORM_DIRECTIVES } from 'angular2/common';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {LoginService} from '../../services/loginService';
import {Router} from 'angular2/router';

@Component({
    selector: 'login',
    providers: [HTTP_PROVIDERS]
})
@View({
    templateUrl: '/scripts/src/components/login/login.html',
    directives: [FORM_DIRECTIVES]
})

export class LoginComponent {
    userName: string;
    password: string;
    showError: boolean;
    constructor(
        @Inject(LoginService) private loginService: LoginService,
        @Inject(Router) private router: Router
    ) {
        this.userName = '';
        this.password = '';
        this.showError = false;
    }
    login() {
        var data = {
            userName: this.userName,
            password: this.password
        }
        this.loginService.login(data, (res) => {
            this.showError = false;
            // and then we redirect the user to the home
            this.router.parent.navigate(['/Home']);
        }, (err) => {
            this.showError = true;
        });
    }
}

登录后我必须设置一些变量,我可以在app组件上访问该变量来隐藏和显示登录链接以及其他任何需要的组件。

angular angular2-routing angular2-services
1个回答
2
投票

使用updating variable changes in components from a service with angular2中显示的服务将其添加到bootstrap(AppElement, [..., NameService]);中的提供,并将nameService: NameService参数添加到要访问值的组件的构造函数中。

@Injectable()
class NameService {
  name: any;
  nameChange: EventEmitter = new EventEmitter();
  constructor() {
    this.name = "Jack";
  }
  change(){
    this.name = "Jane";
    this.nameChange.emit(this.name);
  }
}

... 
var _subscription;
constructor(public nameService: NameService) {
  this.name = nameService.name;
  _subscription = nameService.nameChange.subscribe((value) => { 
    this.name = value; 
  });
}

ngOnDestroy() {
  _subscription?.unsubscribe();
}
© www.soinside.com 2019 - 2024. All rights reserved.