可能有两个模板在AngularJS 2单呼叫服务 [英] Is possible to have two template for single call service in AngularJS 2
问题描述
我的服务回报项目的两个列表,我想呈现每个列表中选择不同的
My service return two list of items and I want to render each list to difference selector
this.http.get(url).map(res => res.json())
json的回报 {list1的:[...],列表2:[...]}
和我有两个< DIV>
渲染 list1的
和列表2
。
是否有可能做角JS 2?
Is it possible to do with Angular JS 2?
推荐答案
我不知道你是怎么引发的号召你的要求。另一个组件,例如
I don't know how you trigger the call for your request. Another component for example.
您也可以定义两个 EventEmitter
属性(每个列表中的一个)到您的服务发出事件当你的HTTP调用的响应是存在的。两个组件都可以在其订阅到被通知当数据在那里。
You could also define two EventEmitter
properties (one per list) into your service to emit events when the response of your HTTP call is there. Two components can subscribe on it to be notified when data are there.
-
Service实现
Service implementation
export class ListService {
list1Event: EventEmitter<any> = new EventEmitter();
list2Event: EventEmitter<any> = new EventEmitter();
getLists() {
return this.http.get(url).map(res => res.json())
.subscribe(
(data) => {
this.list1Event.emit(data.list1);
this.list2Event.emit(data.list2);
}
);
}
}
组件#1日实施
Component #1 implementation
@Component({
selector: 'my-component1',
template: `
<ul>
<li *ngFor="#item of list">{{item.name}}</li>
</ul>
`
})
export class MyComponent1 {
constructor(private service:ListService) {
this.service.list1Event.subscribe.(data => {
this.list = data;
});
}
}
组件#2实现(类似但对于列表2)
Component #2 implementation (similar but for list2)
组件触发HTTP调用的执行
Component that triggers the execution of the HTTP call
@Component({
selector: 'other-component',
template: `
<div (click)="executeRequest()">Execute request</div>
`
})
export class OtherComponent {
constructor(private service:ListService) {
}
executeRequest() {
this.service.getLists();
}
}
有关详细信息,请参阅此问题:
See this question for more details:
- Delegation: EventEmitter or Observable in Angular2
这篇关于可能有两个模板在AngularJS 2单呼叫服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!