如何在Angular 6中同步加载组件?

Smo*_*oth 3 angular angular6

我有一个标头组件,该组件进行调用以获取用户令牌并存储用户的数据。然后,我有一个不同的组件(管理组件),它不是标头的子代,它依赖于用户数据来获取其他数据。我遇到的问题是管理组件在标头组件完成对用户的调用之前初始化,因此破坏了我的管理组件。换句话说,由于标题尚未设置活动公司,因此代码执行中断。有没有办法确保这些在Angular 6中同步加载,这样我就可以避免此问题?

header.component.ts

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


@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  user: any;
  activeCompany: any;

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authService.getToken().then((user) => {
      this.user = user;
      this.user.Companies = JSON.parse(this.user.Companies.split('"').join('"'));
      this.authService.getActiveCompany$().subscribe((company: any) => {
        if(!company) {
          let company = this.user.Companies[0]
          this.authService.setActiveCompany$(JSON.stringify(company));
        }
        this.activeCompany = company;
      });
    });
  }

  setActiveCompany(company) {
    this.authService.setActiveCompany$(company)
  }
}
Run Code Online (Sandbox Code Playgroud)

admin.component.ts

import { Component, OnInit } from '@angular/core';
import { TagService } from '../../services/tag.service';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
  companyId: number;
  tags: any;
  loading: boolean = true;

  constructor(
    private tagService: TagService,
    private authService: AuthService
   ) {}

  ngOnInit() {
    this.authService.getActiveCompany$().subscribe((company: any) => {
      // The line below breaks because the active company has not been set yet by the header 
      this.companyId = company.Id
      this.tagService.getTags(companyId).then((tags) => {
        this.setTags(tags)
        this.loading = false;
      });
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

验证服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { AppConfig } from '../../app-config';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private activeCompany$: Subject<any>;

  constructor(private http: HttpClient, private _config: AppConfig) {
    let initialActiveCompany;
    if (window.localStorage.getItem('activeCompany')) {
      initialActiveCompany = JSON.parse(window.localStorage.getItem('activeCompany'));
}   else {
      this.getToken().then((user: any) => {
        initialActiveCompany = user.Companies = JSON.parse(user.Companies.split('&quot;').join('"'))[0];
  });
}
this.activeCompany$ = new BehaviorSubject<any>(initialActiveCompany);
Run Code Online (Sandbox Code Playgroud)

}

  getToken() {
    return new Promise(resolve => {
      this.http.get(`${this._config.API_URL}/Token`).subscribe(data => {
        resolve(data);},
        err => {
        console.log("Error retrieving token", err);
      });
    });
  }

  // Returns the observable (read-only) part of this subject
  getActiveCompany$(): Observable<any> {
    return this.activeCompany$.asObservable();
  }

  // Stores the new company value in local storage and pushes it to the subject
  setActiveCompany$(company: any) {
    window.localStorage.setItem('activeCompany', JSON.stringify(company));
    this.activeCompany$.next(company);
  }
}
Run Code Online (Sandbox Code Playgroud)

Viv*_*mar 5

我认为您应该多组织一些服务来处理异步性。

你应该做的activeCompanyBehaviorSubject在AuthService,然后认购管理变革。

因为getTags()无论何时activeCompany更改,您都需要调用。