Angular2 ..使用相同的组件在同一页面上显示不同的数据,具体取决于服务响应/重用组件 [英] Angular2 .. Using the same component to show different data on the same page depending on service response / Reusing Component

查看:258
本文介绍了Angular2 ..使用相同的组件在同一页面上显示不同的数据,具体取决于服务响应/重用组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要HTML

<div>
  <block></block>
  <block></block>
</div>

我的组件

import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
    selector : 'block',
    template : `
      <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}}</div> 
`,
providers : [HTTP_PROVIDERS,TestService]
})
export class TestComponent implements OnInit{
    _list : any[];
    constructor(private _testDataService : TestService){}
    ngOnInit(){
        this._testDataService.getData()
            .subscribe(list => this._list = list);
    }

}

我想重复使用同一页面中的组件以针对不同的服务调用显示不同的数据

I want to reuse the component in the same page to show different data for different service calls

推荐答案

我们可以通过将视图中的数据作为属性传递到Component来实现此目的.

We can achieve this by passing data from view to the Component as an attribute.

<div>
  <block test="block1"></block>
  <block test="block2"></block>
</div>

然后使用@Input装饰器在组件中获取test的值

Then in the component get the value of test by using the @Input decorator

import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
  selector : 'block',
  template : `
    <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}} 
    </div> 
    `,
  providers : [HTTP_PROVIDERS, TestService]
})
export class TestComponent implements OnInit{

  @Input() test;

  _list : any[];

  constructor(private _testDataService : TestService){}

  ngOnInit(){
    this._testDataService.getData(this.test)
      .subscribe(list => this._list = list);
  }
}

从视图中接收到值后,根据获取数据的方式将其传递给服务.

After receiving the value from view, pass the same to the service depending on which you get the data.

只要angular在视图中看到选择器,就会创建该选择器的新实例.

Wherever angular sees a selector in the view, it will create a new instance of that.

这篇关于Angular2 ..使用相同的组件在同一页面上显示不同的数据,具体取决于服务响应/重用组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆