在AngularJS 2中可以有两个用于单个呼叫服务的模板

时间:2016-03-03 01:28:05

标签: angular

我的服务返回两个项目列表,我想将每个列表呈现给差异选择器

this.http.get(url).map(res => res.json())

json返回{ list1: [...], list2: [...] }

我有两个<div>来呈现list1list2

是否可以使用Angular JS 2?

2 个答案:

答案 0 :(得分:0)

class MyService {
  private _list1;
  private _list2;

  getList1() {
    if(this._list1) {
      return Observable.of(this._list1);
    } else {
      return _getList(1);
    }
  }

  getList2() {
    if(this._list2) {
      return Observable.of(this._list2);
    } else {
      return _getList(2);
    }
  }

  private _getList(listNo) {
    return this.http.get(url).map(res => {
      var json = res.json();
      this._list1 = value.list1;
      this._list2 = value.list2;
      if(listNo == 1) {
        return json.list1;
      }
      if(listNo == 2) {
        return json.list2;
      }
    });
  }
}
@Component({
  selector: 'my-component1',
  pipes: [KeysPipe],
  template: `
  <ul>
     <li *ngFor="let item of list | keys">{{item.key}} - {{item.value}}</li>
  </ul>
`
})
export class MyComponent1 {
  constructor(private MyService myService) {
    myService.getList1().subscribe.(value => this.list = value);
  }
}
@Component({
  selector: 'my-component2',
  pipes: [KeysPipe],
  template: `
  <ul>
     <li *ngFor="let item of list | keys">{{item.key}} - {{item.value}}</li>
  </ul>
`
})
export class MyComponent2 {
  constructor(private MyService myService) {
    myService.getList2().subscribe.(value => this.list = value);
  }
}

如果要在同一个组件中渲染两个列表,当然可以简化它们。

对于KeysPipe,请参阅access key and value of object using *ngFor

答案 1 :(得分:0)

我不知道你是如何触发你的请求的电话。例如,另一个组成部分。

您还可以在服务中定义两个EventEmitter属性(每个列表一个),以便在HTTP调用的响应存在时发出事件。有两个组件可以在其上订阅,以便在数据存在时得到通知。

  • 服务实施

    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({
      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实现(类似但是对于list2)

  • 触发执行HTTP调用的组件

    @Component({
      selector: 'other-component',
      template: `
        <div (click)="executeRequest()">Execute request</div>
      `
    })
    export class OtherComponent {
      constructor(private service:ListService) {
      }
    
      executeRequest() {
        this.service.getLists();
      }
    }
    

有关详细信息,请参阅此问题: