Angular 4 UI未从可观察订阅更新

时间:2017-10-30 15:25:11

标签: angular angular2-services

我在我的应用程序组件中订阅的服务中有一个observable。数据正在通过订阅传递没有问题,但由于某种原因我无法使用新信息更新UI。我知道数据已经到达那里,因为它正在登录到控制台。

这是我的app.component代码:

import {Component, OnDestroy, OnInit} from '@angular/core';
import {UserDetailsService} from './services/user-details.service';
import {User} from './shared/models/user';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {

  title = 'the Portfolio';
  user: User;
  userSub: Subscription;

  constructor(public userDetails: UserDetailsService) {
  }

  ngOnInit(): void {
    this.userSub = this.userDetails.user$.subscribe(user => {
      this.user = user;
      console.log(user);
    });
  }

  ngOnDestroy() {
    this.userSub.unsubscribe();
  }
}

我更新observable的用户登录组件:

import {Component, AfterViewInit, NgZone} from '@angular/core';
import {UserDetailsService} from '../services/user-details.service';
import {User} from '../shared/models/user';

declare const gapi: any;

@Component({
  selector: 'app-user-login',
  templateUrl: './user-login.component.html',
  styleUrls: ['./user-login.component.css']
})

export class UserLoginComponent implements AfterViewInit {

  constructor(private _zone: NgZone, private userDetails: UserDetailsService) {
    console.log(this);
  }

  ngAfterViewInit() {
    gapi.load('auth2', () => {
      const auth = gapi.auth2.init({
        'clientId': 'YOURID.apps.googleusercontent.com'
      });

      auth.attachClickHandler('google-login-button', {},
        (googleUser) => {
          const profile = googleUser.getBasicProfile();
          // console.log('Token || ' + googleUser.getAuthResponse().id_token);
          // console.log('ID: ' + profile.getId());
          // console.log('Name: ' + profile.getName());
          // console.log('Image URL: ' + profile.getImageUrl());
          // console.log('Email: ' + profile.getEmail());

          this.userDetails.setLoginUser(new User({
            id: profile.getId(),
            name: profile.getName(),
            email: profile.getEmail()
          }));
        },
        (error) => {
          alert(JSON.stringify(error, undefined, 2));
        });
    });
  }
}

用户详细信息服务:

import {Injectable, OnInit} from '@angular/core';
import {User} from '../shared/models/user';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/map';

@Injectable()
export class UserDetailsService implements OnInit {

  private userSubject = new BehaviorSubject<User>(new User());
  user$ = this.userSubject.asObservable();

  constructor() {
  }

  ngOnInit(): void {
  }

  public setLoginUser(user: User) {
    this.userSubject.next(user);
  }
}

这是我的UI代码:

<div *ngIf="user" class="alert alert-success">{{user.name}}</div>
{{user.name}}

我错过了什么?现在已经坚持了一天多了。

任何帮助表示感谢,提前谢谢。

2 个答案:

答案 0 :(得分:0)

发现问题。当我使用setLoginUser函数更新服务时,我这样做了:

this.userDetails.setLoginUser(new User({
              id: profile.getId(),
              name: profile.getName(),
              email: profile.getEmail()
            }));

我需要这样做:

this._zone.run(() =>{
            this.userDetails.setLoginUser(new User({
              id: profile.getId(),
              name: profile.getName(),
              email: profile.getEmail()
            }));
          });

现在两种方式都有效:

<div *ngIf="user" class="alert alert-success">{{user.name}}</div>
{{(userDetails.user$ | async).name}}

感谢您的帮助!

答案 1 :(得分:0)

我不确定您是否需要该区域运行,因为在我的应用程序中类似的情况下我并不需要。我在服务中使用getter和setter方法。你能在这里查看https://github.com/JanneHarju/MultiSourcePlayList/blob/master/angular2App/app/services/playlist.service.ts getPlaylistsModified()函数。