Angular 5服务中的同步http get请求?

问题描述 投票:0回答:2

我有一个非常大的项目,有很多组件和服务。

我想构建所有组件使用的另一个服务。该服务将调用http get请求,该请求检索组件的顺序(如配置),并据此在页面上对组件进行排序。我想使调用同步,以便在检索订单之前不加载组件。我想这样做是因为我不希望在加载组件后闪烁显示。基本上就像一个同步的ajax调用。

我的代码如下

服务

import { Injectable } from "@angular/core";

@Injectable()

export class ConfigService {
    constructor() {

    }
    getUserConfigFromDB() {
        //http request
        ;

    }
}

零件

import { Injectable } from "@angular/core";
import {ConfigService} from "../app/services/ConfigService"

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

export class AppComponent {
  title = 'app';

  constructor(private configService: ConfigService) { }

  ngOnInit() {
    this.configService.getUserConfigFromDB()
  }
}

这项服务将被许多组件使用。

先感谢您。

编辑1:我想我不清楚。除了调用getUserConfigFromDB()方法之外,我无法更改组件中的任何内容。我正在寻找ajax(async:false)的确切替代品。我希望页面冻结,直到我得到api的响应。

angular angular5 angular-services
2个回答
3
投票

不要使用同步http请求,只需将http请求放入解析器即可。在解析器获取数据之前,页面不会加载,因此您不会得到您正在谈论的闪烁。


0
投票

理想情况下,你应该创建一个ContainerComponent。这个ContainerComponent将调用你正在谈论的方法,并将配置作为ContainerComponent类的属性。

然后,您可以将所有组件放在divContainerComponent模板中,并在其上放置*ngIf。只有在调用服务方法后设置了config时才会显示。

我不确定你是如何计划使用这个config来订购组件的。

© www.soinside.com 2019 - 2024. All rights reserved.