Angular 2-从本地json获取数据以填充下拉列表 [英] Angular 2 - fetch data from local json to populate dropdown

查看:66
本文介绍了Angular 2-从本地json获取数据以填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Angular 2服务,该服务使用http读取本地json(稍后可能会调用rest服务)并返回一个Observable.

I have created a Angular 2 service which reads a local json using http (could be rest service call later) and returns an Observable.

   @Injectable()
   export class WorkflowDataService {
   constructor(private http: Http) { }
   getProcessTemplates(): Observable<Response> {
       return this.http.get("/assets/jsons/process-templates.json");
   }}

正在读取的json看起来像这样

the json that is being read looks like this

{
"process-templates": [
    {
        "name": "ABC",
        "desc": "ABC"
    },
    {
        "name": "XYZ",
        "desc": "XYZ"
    },
    {
        "name": "PQR",
        "desc": "PQR"
    }
 ]
}

我的目标是在下拉列表中显示名称属性的值.因此,下拉列表应具有-ABC,XYZ和PQR.

My goal is to show the values of name attributes in a dropdown. So, the dropdown should have - ABC, XYZ, PQR.

因此,在我的组件中,我正在调用此服务-

So in my component, I am calling this service -

processTemplates: Observable<Response>; 
ngOnInit( ) {
  this.workflowDataService.getProcessTemplates()
     .subscribe(function(response) {
       this.processTemplates = response.json();
       console.log(this.processTemplates);
     });
}

在console.log中,我看到以下输出

In the console.log, I see the below output

如何获得可以下拉显示的格式的输出

how can I get the output in a format which can be rendered in a drop down

<select class="form-control dropdown" (ngModel)="processTemplate" 
                name="processTemplate" id="processTemplate" required>
              <option *ngFor="let processTemplate of processTemplates">
                {{ processTemplate.name }}
              </option>
            </select>

推荐答案

您的JSON在对象内部包含一个数组,因此您需要从对象 process-templates 中提取该数组.还进行了其他一些更改,而不是使用胖箭头语法而不是 function ,因此您不会丢失上下文 this :)

Your JSON contains an array inside a object, so you need to extract the array from the object process-templates. Made some other changes as well, rather use fat arrow syntax instead of function, so you don't loose the context this :)

selectedT: any;

getProcessTemplates(): Observable<Response> {
   return this.http.get("/assets/jsons/process-templates.json")
     // extract array from process-templates object
     .map(res => res.json().process-templates) 
}}

然后在您的组件中订阅:

Then in your component subscribe:

this.workflowDataService.getProcessTemplates()
  .subscribe(data => {
    this.processTemplates = data;
    console.log(this.processTemplates);
  });

关于模板,就像约翰说的那样:

And as for your template, do like John said:

<select [(ngModel)]="selectedTemplate"> 
  <option *ngFor="let processTemplate of processTemplates">{{processTemplate.name}}</option>
</select>

这篇关于Angular 2-从本地json获取数据以填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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