首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绑定到我的Angular 2应用程序中正确的服务调用

绑定到我的Angular 2应用程序中正确的服务调用
EN

Stack Overflow用户
提问于 2017-02-04 02:12:01
回答 2查看 574关注 0票数 0

在我的Angular 2应用程序中,我有几个不同的组件来显示不同组的数据。每个不同的组都有不同的API服务调用。但是,除了不同的数据集之外,每个数据集的表格显示/布局本身都是相同的。

在每个组的组件中,我像这样使用服务调用(这个调用用于"group1")。我在我的group1.component.ts中订阅我的OnInit中的数据:

代码语言:javascript
复制
ngOnInit() {
    this.group1Service.getGroup()
        .subscribe(resRecordsData => this.records = resRecordsData,
        responseRecordsError => this.errorMsg = responseRecordsError);
}

现在,我想要做的是通过抽象出表格显示来减少重复(即让它变干),这样我就可以把它作为一个子视图放到每个组件视图中。例如,组件1的视图如下所示("table-display“是在下面的代码中抽象出来的部分):

代码语言:javascript
复制
<div class="page-view">
    <div class="page-view-left">
        <comp1-left-panel></comp1-left-panel>
    </div>
    <div class="page-view-right">
        <div class="page-content">
            <table-display></table-display>
        </div>
    </div>
</div>

我的问题是,如何将正确的服务调用(即正确的组件)绑定到每个组件的"table-display“?我应该在这里使用@Input,或者使用方括号绑定吗?

EN

回答 2

Stack Overflow用户

发布于 2017-02-04 03:51:27

是的,您将在表格显示组件上使用输入,并从父组件填充它:

代码语言:javascript
复制
<table-display [Data]="arrayOfData"></table-display>

在表中定义数据的位置-显示为:

代码语言:javascript
复制
@input Data: Array<any>;
票数 1
EN

Stack Overflow用户

发布于 2017-02-04 03:53:53

您可以将所需数据作为Input传递给table-display组件。

如果所有组件共享相同类型的结构以在表中显示数据。然后,我建议为公共数据创建一个单独的类,并传递该公共类的对象。

您可以在每个组件中编写一个映射器函数,该函数将向table-display返回所需的数据,或者,如果它是一个简单的类似JSON的结构,那么您可以动态地传递它。

e.g

假设有4个属性需要在表显示中显示,我们创建了common.ts

代码语言:javascript
复制
export class Common {
col1: string; #whatever data structure you need
col2: number;
col3: number[];
col4: Object;
constructure(col1: any,col2: any,col3: any,col4: any){
this.col1 = col1;
//set other attributes similarly

}

}

component1.component.ts中为否

代码语言:javascript
复制
import {Common}  from './path_to_common.ts'
#other imports here
@component {
selector: 'app-component1',
template: "your about template"
}
export class Component1Component implements OnInit{

common: Common; #this is the common attribute you will pass to **table-display**

constructure(component1_service: Component1Service){
}

ngOnInit(){

#get your data from service here
#now set **common** attribute here by settings 4 attributes we defined
#e.g
this.common = new Common(service_record.col1,service_record.col2....)
}

}

就是这样,现在您可以通过以下方式将此common属性作为输入传递:

在组件模板中

代码语言:javascript
复制
<table-display [common]="common"></table-display>

现在编写TableDisplayComponent

代码语言:javascript
复制
import {Input} from '@angular/core'
`import {Common}  from './path_to_common.ts'
#other imports here
@component {
selector: 'table-display'
template: `what ever your template is to show table`
}

export class TableDisplayComponent{

@Input() common: Common; #This common will be passed as input from all of your components
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42030487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档