Angular:在更改路径时显示组件中的加载条

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

不确定实现这一目标的最佳方法是什么。

我在这个URL上有一个项目列表:http://localhost/items

items list

当用户单击编辑按钮(比如项目2按钮)时,它将更改到http://localhost/items/item2的路径

现在我想从数据库中获取所选项目的信息并显示详细信息。在等待来自服务器的数据时,我想显示放置项目列表的加载进度,同时显示菜单和信息组件。像这样:

loading

我曾经这样做的一种方法是简单地加载ItemDetails组件,显示加载标签,提出获取详细信息的请求以及何时收到数据我隐藏加载标签。

  ngOnInit() {
    this.loading = true;
    const itemID = this.route.snapshot.paramMap.get('id');
    this.itemsService
        .getItem(itemID)
        .subscribe(restult => {
            //process result
            this.loading = false;
        });
  }

这种方法效果很好,但我不确定这是否是反模式。

我尝试的第二种方法是使用解析器获取项目信息并依赖路由器事件(NavigationStartNavigationEnd)来显示加载标签。

这种方法的问题是当用户在浏览器中输入项目详细信息URL时(不单击编辑按钮):http://localhost/items/item2。它将等到收到数据然后将呈现所有组件(菜单,信息,当然还有项目详细信息)。

那么,可以使用第一种方法还是反模式?如果它是反模式,那么使用解析器或任何其他方法解决此问题的最佳方法是什么,我能够在检索数据时显示某些组件(菜单,加载栏)?

angular angular-router
1个回答
0
投票

您也可以使用npm包,因此您不需要为每个请求设置加载标志,这是npm包示例。

包装:https://www.npmjs.com/package/ng-http-loader

$ npm install ng-http-loader --save / yarn add ng-http-loader

在AppModule中:

`import { BrowserModule } from '@angular/platform-browser';
 import { NgModule } from '@angular/core';
 import { AppComponent } from './app.component';
 import { HttpClientModule } from '@angular/common/http';
 import { NgHttpLoaderModule } from 'ng-http-loader';

 @NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule, // <============ (Perform HTTP requests with this module)
        NgHttpLoaderModule.forRoot(), // <============ Don't forget to call 'forRoot()'!
    ],
    providers: [],
        bootstrap: [AppComponent]
})
export class AppModule { }`

在app.component.html中

<ng-http-loader></ng-http-loader>

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