【问题标题】:Angular2 How to protect contentAngular2如何保护内容
【发布时间】:2016-02-22 03:41:43
【问题描述】:

我想实现一些非常简单的登录尝试应用良好的 OOP 概念,但是我不能在组件之间共享变量。

基本我有一个主组件,它有两个子组件 Login 和 ProtectedComponent,流程是当一个人被记录时,我想隐藏登录组件并显示受保护的组件。你可以看到下面的代码。

import {bootstrap, Component, View, NgIf} from 'angular2/angular2';

//Protected-Content Component
@Component({
  selector: 'protected-content'
})
@View({
  templateUrl: 'app/views/protected-component.html'
})
class ProtectedComponent{
}


//Login Component
@Component({
  selector: 'login'
})
@View({
  templateUrl: 'app/views/login.html'
})
class Login{
  login(username, password){
    if(username.value =="test" && password.value=="test"){
      isLogged = true;
    }
  }
}

@Component({
  selector: 'main'
})
@View({
  template:`
  <login *ng-if="!isLogged"></login>
  <protected-content *ng-if="isLogged"></protected-content>`,
  directives:[Login,ProtectedComponent,NgIf]
})
class Main{
  isLogged:boolean;
  constructor(){
    this.isLogged = false;
  }
}

bootstrap(Main);

有什么想法吗?

【问题讨论】:

  • 我认为您无法保护前端的内容。例如,Chrome 中的控制台可以从 Firebase 读取配置

标签: angular typescript angular2-forms


【解决方案1】:

或者扩展RouteOutlet类,如果登录失败,使用instruction.component = Login将用户路由到Login组件(可以通过扩展类中的静态isLogged:boolean检查)。

https://auth0.com/blog/2015/05/14/creating-your-first-real-world-angular-2-app-from-authentication-to-calling-an-api-and-everything-in-between/

【讨论】:

    【解决方案2】:

    我为此使用了EventEmiter,它允许组件之间进行通信。这里很好example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-27
      • 2012-01-19
      • 2012-03-02
      • 2011-02-20
      • 2010-09-24
      • 1970-01-01
      • 2011-02-26
      • 2018-02-02
      相关资源
      最近更新 更多