创建一个具有属性的对象,以存储loggedIn用户信息并绑定/更新它们以进行查看

时间:2016-02-18 13:21:16

标签: angular

注意:请忽略此帖子的语法错误。
我的项目设置如下。

  

boot.ts < = ParentComponet,$CorePath = dirname(__DIR__) . '/fod/' . strtolower($class_name) . '.php'; &子组件,   包含子代理的导航。
----- Home.ts &lt; =   默认视图使用<routerOutlet>
----- login.ts &lt; =但是   覆盖useAsDefault,我检查用户是否经过身份验证或   不。如果不是(显然这里),请加载登录组件。

models.ts

routerOutlet

authService.ts

export class UserModel()
{
    private userName:string;
    private isLoggedIn:boolean;
}

login.ts       ......

import {UserModel} '.../models.ts'
...
...
public let um=new UserModel();  // I don't know how to go ahead from here.
constructor()
{
  um.userName="Guest";
  um.loggedIn=true;  // lets not deal with it for now.
}

setUserDetail(username:string)
{  

   um.userName=username;
   um.loggedIn=true;


   Please note here that when it changes um model, I want to update boot.html view
}

getUserDetail:UserModel()
{
  return um;
}

authentication(username:string,password:string)
{   
        ...// I have http server call here. but not shown.
        ... //database query
        um.userName= "field from DB";
        um.loggedIn=true;
        ...//return observable
 }

boot.ts

login(username,password)
{
  auth.authentication(username,password)
  .subscribe(() => {
     auth.setUserDetail(username);  // this should update boot.html view immediately.
  });
}

boot.html

import {UserModel} '.../models.ts';
import {authService} '.../authService.ts';

constructor(auth:authService)
{
    console.log(auth.getUserDetail());  //log is correct. no problem till here.

   // Note: When we run the app, it may get UserModel object and display to VIEW. But after login how can I update boot.html view?

    1) how to bind upcoming object value to view?
    2) when page is refreshed same object should be returned.         
}

我需要使用... <li ngIf="{{um.loggedIn}}">{{um.userName}}</li> ... 吗?

http://plnkr.co/edit/uPb0eHXPke41zSa9IBdS?p=preview
这显示了如何使用共享服务更新两个视图。

如果有人有兴趣了解覆盖EventEmitter的话 Angular 2 Authentication with child routes

1 个答案:

答案 0 :(得分:0)

我发现你的login方法的代码有点奇怪。我会用它来定义提供给subscribe方法的回调:

login(username,password)
{
  auth.authentication(username,password)
  .subscribe(() => {
     auth.setUserDetail(username);  // this should update boot.html view immediately.
  });
}

修改

您可以在服务中使用EventEmitter属性。有关详细信息,请参阅此链接: