【问题标题】:Angular 2 dropdown list not loading since the http response is slowAngular 2 下拉列表未加载,因为 http 响应很慢
【发布时间】:2018-01-31 09:40:01
【问题描述】:

我试图使用 angular2 服务从 http 响应加载下拉列表。

这是我的服务方法:

categories: any;
    getCategories() {
        let subscription = this.httpclient
          .get(this.server_url)
          .subscribe((data) => {
            this.categories = data;
            console.log(this.categories);
          });
      }

组件传输

categoryID: number;
constructor(public categoryservice: CategoryService) { }

  ngOnInit() {
    this.categoryservice.getCategories();
  }

而组件的html代码是:

<select data-width="20%" class="selectpicker" [(ngModel)]="categoryID">
       <option *ngFor="let category of categoryservice.categories" value= {{category.categoryId}} >{{category.categoryName}}</option>
 </select>

但由于 getCategories() 方法中的响应需要一段时间,因此下拉列表为空。如果响应来得快,列表加载正确。

当响应需要时间从服务器获取数据时,任何人都可以在这种情况下帮助我吗?回复后如何加载列表?

【问题讨论】:

    标签: angular html-select angular2-services angular2-directives


    【解决方案1】:

    您可以将 select 包裹在另一个 divng-container 周围,然后检查数据是否存在,然后仅显示 select 选项。

    喜欢

    <ng-container *ngIf = "categoryservice?.categories">
    <select data-width="20%" class="selectpicker" [(ngModel)]="categoryID">
           <option *ngFor="let category of categoryservice.categories" value= {{category.categoryId}} >{{category.categoryName}}</option>
     </select>
    </ng-container>
    

    【讨论】:

    • 尝试了同样的方法。但没有运气。虽然数据在 2 秒后收到,但
    【解决方案2】:

    您可以在响应带有一个简单的 *ngIf 在您的选择后呈现您的下拉列表,而在您可以呈现加载之前:

    <my-loading *ngIf="!loadComplete"></my-loading>
    
    <select *ngIf="loadComplete" data-width="20%" class="selectpicker" [(ngModel)]="categoryID">
           <option *ngFor="let category of categoryservice.categories" value= {{category.categoryId}} >{{category.categoryName}}</option>
    </select>
    

    在您的 TS 中,您只需在通话完成后将 loadComplete 设置为 true

    loadComplete: boolean = false;
    
    getCategories() {
            let subscription = this.httpclient
              .get(this.server_url)
              .subscribe((data) => {
                this.categories = data;
                this.loadComplete = true;
            }, err => {
               this.loadComplete = true;
               alert("An error occurred");
            });
    }
    

    由于您无法加快调用速度,因此您可以在调用完成之前渲染加载。希望对你有帮助

    【讨论】:

    • this.loadComplete = true 没有反映虽然它在收到响应后发生了变化,并且 *ngIf="categoryservice.loadComplete" 仍然是 false 所以
    • 你在使用onPush策略吗?
    • 不使用 onPush。它是一个简单的 rest 服务调用,它返回像 "[{ "categoryId": 2, "categoryName": "asd" }, { "categoryId": 3, "categoryName": "qqq" }, { "categoryId" : 6, "categoryName": "error" }]" 所以我希望它加载到
    • 可能有错误,在我编辑答案时尝试编辑您的代码
    • 请求响应没有错误。没有弹出警报。
    猜你喜欢
    • 1970-01-01
    • 2020-12-28
    • 2016-06-04
    • 1970-01-01
    • 2016-10-30
    • 2018-05-22
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多