【问题标题】:Angular2 - subscribe to Service variable changesAngular2 - 订阅服务变量更改
【发布时间】:2016-06-03 02:28:42
【问题描述】:

我有一个认证服务,它使认证变量等于真或假。

checkAuthentication(){
  this._authService.getAuthentication()
    .subscribe(value => this.authenticated = value);
}

this.authenticated 的值发生变化时如何执行函数? ngOnChanges 没有接受更改。

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    为了让authenticated 保持服务并在您可以使用的组件之间共享它 BehaviorSubject,是value检查不同地方的身份验证,它是subscribe()对变化做出反应的方法......

    class AuthService {
      public authenticated = new BehaviorSubject(null);
      getAuthentication() {
        this._http.get('/authenticate')
          .map(response => response.json())
          .map(json => Boolean(json)) // or whatever check you need...
          .subscribe((value: boolean) => this.authenticated.next(value))
      }
    }
    
    class Component {
      constuctor(private _authService: AuthService) {
        // Only check once even if component is 
        // destroyed and constructed again
        if (this._authService.authenticated.value === null)
          this._authService.getAuthentication();
      }
    
      onSubmit(){
        if (!this._authService.authenticated.value)
          throw new Error("You are authenticated!")
      }
    }
    

    this.authenticated 的值发生变化时如何执行函数?

      this._authService.authenticated
       .subscribe((value: boolean) => console.log(value))
    

    【讨论】:

    • 嗨@Sasxa所以如果我有例如5个组件。 home.component.tsfooter.component.tsnavbar.component.tsx.component.tsuser.component.ts。假设这 5 个组件,如果我想检查是否经过身份验证。我必须将以下内容添加到我的所有 5 个组件中:constructor(private _authService: AuthService) {...}。它是否正确?并为所有 5 个组件执行ngOnInit?需要一些帮助来理解 Angular2 身份验证概念。
    • 有很多选项/选择。这完全取决于你在做什么。您可以在每个组件上进行身份验证,也可以仅在根组件上进行身份验证。这是一个复杂的话题,你需要决定什么最适合你的应用(;
    • 你能给我指点关于这个主题的讨论/论坛/博客/文章吗?
    • 这实际上似乎不适用于最新版本的 Angular 2。有人找到任何解决方案吗?
    【解决方案2】:

    我认为您可以利用 TypeScript 的 get / set 语法来检测您的服务的身份验证属性何时更新:

      private _authenticated:Boolean = false;
      get authenticated():Boolean {
            return this._authenticated ;
      }
      set authenticated ( authenticated Boolean) {
        // Plugin some processing here
          this._ authenticated = authenticated;
      }
    

    当分配一个值时,“set authenticated”块被调用。例如这样的代码:

    this.authenticated = true;
    

    查看这个问题了解更多详情:

    也就是说,您还可以在服务中利用 EventEmitter 属性。当经过身份验证的属性更新时,可能会触发相应的事件。

    export class AuthService {
      authenticatedChange: Subject<boolean> = new Subject();
    
      constructor() {}
    
      emit(authenticated) {
        this.authenticatedChange.next(authenticated);
      }
    
      subscribe(component, callback) {
        // set 'this' to component when callback is called
        return this.authenticatedChange.subscribe(data => {
          callback(component, data);
        });
      }
    }
    

    查看此链接了解更多详情:

    【讨论】:

    • 这是一种好方法吗,因为您建议在设置 authenticated 值时启动一些事件?理想情况下,setter 负责通过将提供的输入值操作到其函数来设置值..
    • 您好 Thierry,我在 Angular.io 网站上搜索了有关 EventEmitter 的文档/教程。但它非常有限。知道在哪里可以找到有关使用 Angular2 EventEmitter 的指导教程吗?
    • 这被认为是不好的做法。推荐的方法是使用 Subject/BehaviorSubject
    • @atsituab 你绝对是对的。我很久以前就回答了这个问题;-) 我相应地更新了我的答案!感谢您指出这一点!
    【解决方案3】:

    这取决于谁需要处理事件。如果它是父组件,您可以利用输出事件绑定:

    @Output authenticationChange: EventEmitter<Boolean> = new EventEmitter();
    checkAuthentication(){
         this._authService.getAuthentication()
         .subscribe(value => 
               if(value != this.authenticated) {
                   this.authenticated = value);
                   this.authenticationChange.emit(value);
          });
     }
    

    在你的父组件中:

     <directive (authenticationChange)="doSomething()">
    

    【讨论】:

      【解决方案4】:

      我在组件模板中使用了{{ showValue() }},在.ts 文件中我调用了服务的变量

      showValue() {
         this.authenticated = this._authService.authenticated;
         return "dummy"
      } 
      

      感谢 Angular2 的 GUI 2-way binding,它可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-21
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        相关资源
        最近更新 更多