简体   繁体   English

从API加载数据后呈现视图-Angular2

[英]Render view after data loading from an API - Angular2

I think this is an easy one. 我认为这很容易。

I have a component in my Angular2 application, with a table feeded by a data parsed from an API. 我的Angular2应用程序中有一个组件,其中的表由从API解析的数据提供。

Everything works fine exept for one thing: when I load my page the data is not present; 一件事一切都很好:当我加载页面时,数据不存在; only after I start a search on my filter the table populates. 只有在我开始对过滤器进行搜索之后,表格才会填充。

The component has this method: 该组件具有以下方法:

getList() {
    return this.service.getList()
        .subscribe(tasks => {
            this.data = tasks
        });
}

to collect the data from the API through a service. 通过服务从API收集数据。 This method is triggered by ngInit() method, but returns undefined. 此方法由ngInit()方法触发,但返回未定义。 Only if I fire the method onChangeTable() I get the results in my view. 仅当我触发onChangeTable()方法时,我才会在视图中获取结果。

I think I should have to preload data before render view ... 我认为我应该在渲染视图之前预加载数据...

Many thanks in advance :) 提前谢谢了 :)

PS Ok, here are my files: 好的,这是我的文件:

Ok, 好,

I post here the solution. 我在这里发布解决方案。

The implementation of a Resolver does the trick. 解析器的实现可以解决问题。

I created a Resolver: 我创建了一个解析器:

import {Resolve, RouterStateSnapshot, ActivatedRouteSnapshot} from "@angular/router";
import {Injectable} from "@angular/core";
import {TaskService} from "../services/task.service";
import {Observable} from "rxjs";

@Injectable()
export class TaskResolver implements Resolve<any> {
    constructor(private service: TaskService) {}

    resolve(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<any>|Promise<any>|any {
        return this.service.getList();
    }
}

Then, I use this Resolver in my Router: 然后,我在路由器中使用此解析器:

...
{path: '', component: ListTaskComponent, resolve: { data: TaskResolver }},

And finally in my component, I can get this: 最后,在我的组件中,我可以得到以下信息:

public constructor(private route:ActivatedRoute) {
    ...
}

public ngOnInit():void {
    this.data = this.route.snapshot.data['data'];
    this.onChangeTable(this.config)
}

Hope that helps guys. 希望对大家有帮助。

Thank you :) 谢谢 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM