热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Angular6中同步加载组件?

如何解决《如何在Angular6中同步加载组件?》经验,为你挑选了1个好方法。

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

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

验证服务

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;

  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('"').join('"'))[0];
  });
}
this.activeCompany$ = new BehaviorSubject(initialActiveCompany);

}

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

Vivek Kumar.. 5

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

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

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



1> Vivek Kumar..:

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

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

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


推荐阅读
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • vue使用
    关键词: ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法
    本文介绍了解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法,包括检查location配置是否正确、pass_proxy是否需要加“/”等。同时,还介绍了修改nginx的error.log日志级别为debug,以便查看详细日志信息。 ... [详细]
  • CEPH LIO iSCSI Gateway及其使用参考文档
    本文介绍了CEPH LIO iSCSI Gateway以及使用该网关的参考文档,包括Ceph Block Device、CEPH ISCSI GATEWAY、USING AN ISCSI GATEWAY等。同时提供了多个参考链接,详细介绍了CEPH LIO iSCSI Gateway的配置和使用方法。 ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 图像因存在错误而无法显示 ... [详细]
author-avatar
-赵-宾-_879
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有