无法将数据获取到UI但获得了控制台

时间:2018-06-29 07:31:44

标签: angular

This is the output i got in the console but i can't able to display it in UI

我想分配客户地址的东西。但是api的编写方式类似于将地址表数据映射到客户表中。所以,我得到的输出就像一个Customer表中的地址列表

因此,如果尝试显示客户表中的地址,则我认为绑定无法正常工作。

任何人都可以解决吗?

谢谢。

使用的角度文件如下。 address.service.ts

@Injectable()
export class AddressService {

  selectedAddress : Address

  constructor(private http: Http) { }

  getCustomerAddress(){
    return this.http.get('http://localhost:49422/api/customer/4/profile');
  }

}

address.component.html

 <div class="col-md-6">
        <button type="button" class="btn btn-lg btn-block btn-primary" style="width: auto" (click)="OnCustomerAddressClick()">
            GetCustomerAddress
        </button><br>


        <table class="table table-sm table-hover">
            <tr *ngFor="let address of addressList">
              <td>
                {{address.Firstname}} - {{address.Lastname}}
              </td>
              <td>
                {{address.Address1}},{{address.Address2}}
              </td>
              <td>
                  {{address.City}},{{address.Postcode}}
                </td>
            </tr>               
          </table>              
    </div>
  </div>

address.component.ts

export class AddressComponent implements OnInit {

  singleAddress: Address
  addressList: Address[];
  errorMessage: string ="";

  constructor(private addressService: AddressService, private http :HttpClient) { }

  ngOnInit() {

  }

  OnCustomerAddressClick(){
    this.addressService.getCustomerAddress()
    .subscribe(
      (response:Response) => {
        this.addressList = response.json();
        console.log(this.addressList);
      },
      (error) => {
        this.errorMessage = "Unable to get Customer Address";
      });
  }

}

1 个答案:

答案 0 :(得分:1)

问题在于您的response是一个对象。并且您正在将response分配给this.addressList。因此this.addressList包含的对象不是数组。

但是您想遍历地址

所以请看这里,我正在将Address分配给this.addressList

this.addressList = response.json().Address;

更改 address.component.ts 中的功能OnCustomerAddressClick(),如下所示。

  OnCustomerAddressClick(){
    this.addressService.getCustomerAddress()
    .subscribe(
      (response:Response) => {
        this.addressList = response.json().Address;
        console.log(this.addressList);
      },
      (error) => {
        this.errorMessage = "Unable to get Customer Address";
      });
  }