在Angular2中更改组件变量后视图未更新

Posted

技术标签:

【中文标题】在Angular2中更改组件变量后视图未更新【英文标题】:View not getting updated after component variable is changed in Angular2 【发布时间】:2016-09-15 21:46:12 【问题描述】:

在 SidebarComponent 中的组件变量 'user' 更新后,视图 user.email 未更新。它在手动页面刷新后工作。 我已将材料设计拆分为单独的组件。侧边栏组件如下

SidebarComponent.ts

import Component from 'angular2/core';
import Router, RouteConfig, ROUTER_DIRECTIVES,CanActivate from 'angular2/router';
import HomeComponent from '../home/HomeComponent'
import DashboardComponent from './DashboardComponent'

@Component(
    selector: 'app-sidebar',
    template: `
      <header class="demo-drawer-header">
          <img src="../app/assets/images/user.jpg" class="demo-avatar">
          <div class="demo-avatar-dropdown">
            <span>user.email</span>
            <div class="mdl-layout-spacer"></div>
            <button id="accbtn" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
              <i class="material-icons" role="presentation">arrow_drop_down</i>
              <span class="visuallyhidden">Accounts</span>
            </button>
            <ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="accbtn">
              <li class="mdl-menu__item">hello@example.com</li>
              <li class="mdl-menu__item">info@example.com</li>
              <li class="mdl-menu__item"><i class="material-icons">add</i>Add another account...</li>
            </ul>
          </div>
        </header>
        <nav class="demo-navigation mdl-navigation mdl-color--blue-grey-800">

          <a class="mdl-navigation__link" [routerLink]="['./Dashboard']"><i class="mdl-color-text--blue- grey-400    material-icons" role="presentation">dashboard</i>Dashboard</a>


          <a class="mdl-navigation__link" [routerLink]="['./Home']"><i class="mdl-color-text--blue-grey-400     material-icons" role="presentation">assignment</i>Tasks</a>

          <a class="mdl-navigation__link" href=""><i class="mdl-color-text--blue-grey-400 material-icons"     role="presentation">delete</i>Trash</a>
        </nav>
    `, 

    directives: [ROUTER_DIRECTIVES,DashboardComponent]
)

export class SidebarComponent  

  user = JSON.parse(localStorage.getItem('profile'));  

  constructor() 

我有一个自定义路由器插座来检查用户身份验证,如下所示

import Directive, DynamicComponentLoader, ElementRef from "angular2/core";
import AuthService from '../../services/AuthService'
import Router, RouterOutlet, ComponentInstruction from "angular2/router";

@Directive(
    selector: 'auth-router-outlet'
)
export class AuthRouterOutlet extends RouterOutlet 
    private _protectedRoutes = 
        'app/**': true,
        'app/home': true,
        'app/dashboard': true,
        'app/about': true
    ;

    constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, private _router: Router, nameAttr:     string, private _authService: AuthService) 
        super(_elementRef, _loader, _router, nameAttr);
    

    activate(nextInstruction: ComponentInstruction): Promise<any> 
        if (this._protectedRoutes[nextInstruction.urlPath])         
            if (!this._authService.loggedIn()) 
                this._router.navigate(['Login']);
            
        

        return super.activate(nextInstruction);
    

aboue 出口使用以下 Authservice.ts 设置 Localstorage 中的 Profile 对象

import Injectable from 'angular2/core';
import ROUTER_DIRECTIVES, Router from "angular2/router";
import tokenNotExpired from 'angular2-jwt';


declare var Auth0Lock: any;

@Injectable()
export class AuthService 

constructor(private router: Router) 

  private useremail;

  lock = new Auth0Lock('KEY','URL');

  login() 
   this.lock.show((error: string, profile: Object, id_token: string) => 
     if (error) 
       console.log(error);
       return false;
     

     localStorage.setItem('profile', JSON.stringify(profile));
     localStorage.setItem('id_token', id_token);

     /*var profiletemp = JSON.parse(localStorage.getItem('profile'));
     this.setUserEmail(profiletemp.email);*/

     this.router.navigate(['Dashboard']);

    );
 

 logout() 
   localStorage.removeItem('profile');
   localStorage.removeItem('id_token');
 

 loggedIn() 
    return tokenNotExpired();
  

/* setUserEmail(val)          -- not required as profile object is in localstorage
        this.useremail = val;
   

 getUserEmail() 
        return this.useremail;
   */ 

index.html

<html>
  <head>
    <title>MEAN</title>
    <base href="/"/>

    <!-- 1. Load libraries -->
    <script src="libs/angular2/bundles/angular2-polyfills.js"></script>
    <script src="libs/systemjs/dist/system.src.js"></script>


    <script src="libs/rxjs/bundles/Rx.js"></script>
    <script src="libs/angular2/bundles/angular2.dev.js"></script>
    <script src="libs/angular2/bundles/router.dev.js"></script>
    <script src="//cdn.auth0.com/js/lock-9.0.min.js"></script>
    <script src="libs/angular2/bundles/http.dev.js"></script>
    <script src="https://code.getmdl.io/1.1.3/material.min.js"></script>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"></    meta>

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="app/assets/images/android-desktop.png"></meta>

     <!-- Add to homescreen for Safari on ios -->
    <meta name="apple-mobile-web-app-capable" content="yes"></meta>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"></meta>
    <meta name="apple-mobile-web-app-title" content="Material Design Lite"></meta>
    <link rel="apple-touch-icon-precomposed" href="app/assets/images/ios-desktop.png">

    <!-- Tile icon for Win8 (144x144 + tile color) -->
    <meta name="msapplication-TileImage" content="app/assets/images/touch/ms-touch-icon-144x144-precomposed.png"><    /meta>
    <meta name="msapplication-TileColor" content="#3372DF"></meta>

    <link rel="shortcut icon" href="app/assets/images/favicon.png">


   <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,    bolditalic,black,medium&amp;lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.cyan-light_blue.min.css"> 
    <link rel="stylesheet" href="app/assets/styles.css">
    <style>
    #view-source 
      position: fixed;
      display: block;
      right: 0;
      bottom: 0;
      margin-right: 40px;
      margin-bottom: 40px;
      z-index: 900;
    
    </style>

    <!-- 2. Configure SystemJS -->
    <script>
      System.config(
        packages:         
          app: 
            format: 'register',
            defaultExtension: 'js'
           
         ,
        map: 
          "angular2-jwt": "libs/angular2-jwt/angular2-jwt.js"
        
      );
      System.import('app/bootstrap')
            .then(null, console.error.bind(console));
    </script>

  </head>
  <!-- 3. Display the application..All ExpressJS requests come to this index file and from here Angular routing     takes over-->
  <body>
    <my-app>Loading the application...</my-app>
  </body>

</html>    

我在索引中包含了 angular2-polyfills.js。 SidebarComponent 视图在组件中的相应变量更改后不会更新。

有什么想法吗?

【问题讨论】:

【参考方案1】:

我认为您需要通知SidebarComponent 组件profile 在本地存储中已使用AuthService 共享服务进行了更新。确保在引导您的应用程序时配置此服务。

constructor(private router: Router) 
  private useremail;
  profileUpdated$:Suject<any> = new Subject(); // <-------

  lock = new Auth0Lock('KEY','URL');

  login() 
    this.lock.show((error: string, profile: Object, id_token: string) => 
      if (error) 
        console.log(error);
        return false;
      

      localStorage.setItem('profile', JSON.stringify(profile));
      localStorage.setItem('id_token', id_token);
      this.profileUpdated$.next(profile); // <-------

      this.router.navigate(['Dashboard']);
    );


logout() 
  localStorage.removeItem('profile');
  localStorage.removeItem('id_token');
  this.profileUpdated$.next(null); // <-------

SidebarComponent 组件中,您可以订阅 profileUpdated$ 以收到通知并更新相应的模板:

@Component(
  (...)
)
export class SidebarComponent  

  user = JSON.parse(localStorage.getItem('profile'));  

  constructor(private service:AuthService) 
    this.profileUpdated$.subscribe(profile =>  // <-----
      this.user = profile;
    );
  

【讨论】:

还是一样的行为。我必须手动刷新页面才能重新加载侧边栏。 是否在SidebarComponent 组件中调用了回调? AuthService 服务是否仅在引导应用程序时定义(而不是在组件的providers 属性中)? 我不太明白 SidebarComponent 中的回调?? AuthService 仅在引导程序中,不在任何组件的提供程序中。 我对侧边栏构造函数进行了以下更改 constructor(private service:AuthService) this.user = this.service.profileUpdated$.subscribe(profile => this.user = profile ; ); 现在我不用刷新页面了,只需要点击几下。仍然不完美,但更近了一步。 看这行github.com/auth0/auth0-angular2/blob/master/webpack/src/app/…是来自auth0教程auth0.com/docs/client-platforms/angular2【参考方案2】:

您的localStorage.getItem('profile') 回报是什么。

user = JSON.parse(localStorage.getItem('profile'));

您应该先创建一个用户模型,然后在此模型上分配json result。像这样的

User.ts

export class User 
   email:string;

更改 SidebarComponent.ts 类

export class SidebarComponent  
  user:User ; 
  constructor() 
     this.user=JSON.parse(localStorage.getItem('profile'));  
  

【讨论】:

即使我这样做了,我登录后也不会调用侧边栏构造函数。所以边栏在我登录之前就已经加载了。这就是为什么当我刷新页面时,一切正常。

以上是关于在Angular2中更改组件变量后视图未更新的主要内容,如果未能解决你的问题,请参考以下文章

Angular 2 - 模型更改后视图不更新

Angular 2组件模型刷新视图,无需模型更改

API调用后未更新Angular 2视图

Angular2组件视图不断更新

Core Data 更改时更新 Swiftui 视图

prop 更改时新的 vue 组件实例