Search code examples
angularangular2-services

Angular 4 UI not updating from observable subscription


I have an observable in a service that I have subscribed to in my app component. Data is being passed through the subscription no issues, but for some reason I cannot get the UI to update with the new information. I know that the data is getting there because it is being logged to the console.

Here is my app.component code:

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();
  }
}

User login component where I update the 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));
        });
    });
  }
}

User details service:

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);
  }
}

And here is my UI code:

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

What am I missing? Been stuck on this for over a day now.

Any help appreciated, thanks in advance.


Solution

  • Found the problem. When I was updating the service using the setLoginUser function I did this:

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

    I needed to do this:

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

    Now both ways are working:

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

    Thanks for your help guys!