从api获取数据后,Angular 4视图未更新

时间:2017-06-09 12:02:34

标签: angular typescript

首先,我知道这个问题有很多回复,但我尝试了很多,但没有任何工作。

我使用服务从api端点获取数据,检索数据但之后不再更新视图。

任何人都可以帮助我,谢谢。

details.component.html:

<div class="col-sm-3">
    <div class="well padding-10">
      <h5 class="margin-top-0"><i class="fa fa-shopping-cart"></i> Commande n° {{order?.number}}</h5>
      <ul class="no-padding list-unstyled">
        <li>
          <i class="fa fa-building"></i> <strong>{{order?.site}}</strong>
        </li>
        <li>
          <i class="fa fa-calendar"></i> DATE: {{order?.date}}
        </li>
        <li>
          <i class="fa fa-pencil"></i> RESUME TRAVAUX: {{order?.label}}
        </li>
        <li>
          <i class="fa fa-file-pdf-o"></i> DEVIS: {{order?.quote}}
        </li>
      </ul>
    </div>
  </div>

details.component.ts:

import { Component, OnInit, NgZone } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {OrdersService} from "./orders.service";

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css'],
  providers: [OrdersService],
})

export class DetailsComponent implements OnInit {

  order: any;

  constructor(private _ordersService: OrdersService,
              private _route: ActivatedRoute,
              private _zone: NgZone) { }

  ngOnInit() {
    let id = +this._route.snapshot.params['id'];
    this._ordersService.getOrderWithID(id)
        .subscribe((data)=> {
          this.order = data;
          //this._zone.run(() => this.order = data);
          console.log(this.order);
        });

  }

}

orders.service.ts:

import { Injectable } from '@angular/core';
import {JsonApiService} from "../core/api/json-api.service";
import {Observable} from "rxjs/Rx";

@Injectable()
export class OrdersService {

  url: string;

  constructor(private jsonApiService: JsonApiService) {
    this.url = '/orders';
  }


  getOrderWithID(id: number):Observable<any> {
    return this.jsonApiService.fetch(this.url + '/' + id + '.json');
  }

  getOrders():Observable<any> {
    return this.jsonApiService.fetch(this.url + '/test.json');
  }

}

JSON示例:

{
  "data": [
    {
      "id": 1,
      "date": "31/10/2016",
      "number": XXXXXXXX,
      "site": "XXXXXXXX",
      "label": "XXXXXXXX",
      "amount": "XXXXXXXX",
      "quote": "XXXXXXXX",
      "state": "XXXXXXXX",
      "delivered_at": ""
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

您希望答案中有JSON,但您获得的是Array,所以:

this.order = data[0];应该可以解决问题。