Angular маршрутизация поддерживает отображение предыдущего компонента и не полностью загружает следующий - PullRequest
1 голос
/ 06 февраля 2020

У меня есть компонент, который представляет собой динамически генерируемую таблицу angular, которая должна отображаться по пути «таблица». Но сначала приложение запускается на странице «auth», которая является моей страницей входа. Если аутентификация правильная, я перенаправляюсь в / table без проблем, но: 1) компонент auth по-прежнему отображается 2) таблица не загружена, ngOnInit () не вызывается, похоже, что ни один из кода ts не загружен , только основные c html.

Если я отключу canActivate (), это ничего не изменит, но если я добавлю routerLink в / table в компоненте auth, все будет работать нормально .. .

Это может быть связано с тем, как я аутентифицирую (GoogleAuth), поэтому вот часть кода, хотя я не уверен, что он может быть полезен ..

auth .component.ts

import { Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';


@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {

  constructor(private authService: AuthService, private router: Router){}

 auth2: any;

 
  @ViewChild('loginRef', {static: true }) loginElement: ElementRef;


  ngOnInit() {
 
    this.googleSDK();
 
  }
 
  prepareLoginButton() {
  
    this.auth2.attachClickHandler(this.loginElement.nativeElement, {},
      (googleUser) => {
        
        //ici, l'utilisateur est authentifié
      
        let 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());
        // YOUR CODE HERE

        this.authService.isAuth = true;
        this.router.navigate(['/table']);
              
 
      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });
  }
  googleSDK() {
 
    window['googleSDKLoaded'] = () => {
      window['gapi'].load('auth2', () => {
        this.auth2 = window['gapi'].auth2.init({
          client_id: '88179289847-pcj5c8u563k4igvqof1k65tcbqu4q97f.apps.googleusercontent.com',
          cookie_policy: 'single_host_origin',
          scope: 'profile email'
        });
        this.prepareLoginButton();
      });
    }
    console.log("google sdk");
    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'google-jssdk'));
 
  }
}

auth.guard.ts

import { Injectable, OnInit } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService} from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  ngOnInit(){
  }

  constructor (private authService: AuthService, private router: Router){}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      if(this.authService.isAuth){
        return true;
      } 
      else{
        this.router.navigate(['/auth']);
    }
    return true;
  }
  
}

1 Ответ

0 голосов
/ 06 февраля 2020

Вы выходите за пределы NgZone. Обратный вызов this.auth2.attachClickHandler больше не находится в зоне, поэтому больше нет обнаружения изменений во время маршрутизации. Вы должны обновить свой код, чтобы повторно войти в зону, используя ngZone.run():

constructor(
  private authService: AuthService,
  private router: Router,
  private ngZone: NgZone
){}

this.auth2.attachClickHandler(this.loginElement.nativeElement, {}, (googleUser) => {
  this.ngZone.run(() => {
    // ...
    this.router.navigate(['/table']);
  }); 
});
...