【问题标题】:How to populate the dropdown ,values being returned from observer?如何填充下拉列表,观察者返回的值?
【发布时间】:2020-11-07 04:39:03
【问题描述】:

我将服务中的数据订阅为:

this.infoService.getName()
        .subscribe((data)=>{
            console.log(data.json());
            this.names.push(data.json());
        });

并将其填充到下拉列表中,如下所示:

<select  id='features' name='features'>
    <option *ngFor="let item of names">
      {{item}}
    </option> 
</select>

我的问题是整个响应都排在第 0 位。结果整个响应都出现在下拉列表中,而不是下拉列表中。有人能说我做错了什么吗?

【问题讨论】:

  • My issue is that whole response is coming in 0th position. – 你能澄清一下吗? console.log(data.json()); 的输出是什么?
  • data 的回应是什么?是对象还是数组?
  • @Tommy 输出是一个数组,但我的问题是整个数组都在下拉列表中。相反,它应该以下拉方式排在另一个下方。结果我得到了一个整个宽下拉列表
  • @hbamithkumara 如果我推送(数据)按钮上的输出是 response ok 200........
  • @micronyks 它是一个数组

标签: javascript html angular


【解决方案1】:

假设data 是数组类型。

this.infoService.getName()
        .subscribe((data)=>{
             console.log(data.json());
            
             this.names = data;   // simply assign data array to this.names array 
});

如果Data是字符串数组表示["a", "b", "c"],它会输出名称而不改变html。

如果Data是对象数组[{name:"a"}, {name:"b"}],则将html改成如下,

<option *ngFor="let item of names">
      {{item.name}}                      // check this line
</option>

【讨论】:

  • 数据是字符串数组类型
  • 0: 响应 {_body: "["A","B","C","D"]", status: 200, ok: true, statusText: "OK", headers:标题,...} 长度:1
  • 数据看起来很奇怪。打印不带.json() 并放在这里。
  • 它没有 json
  • 那么它必须是this.names = data[0]._body,但你仍然在某个地方遇到了一些问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多