簡體   English   中英

我無法以角度訪問 object 的屬性

[英]i am not able to access the properties of object in angluar

裝運控制台退回 我正在使用 getshipment 方法通過 id 獲取數據,它返回 object 並像這樣 [object Object] 顯示在前端。 我想訪問詳細信息,然后在前端顯示詳細信息

export class ShipmentInfoComponent implements OnInit {
  shipment: any[];
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private shipmentService: ShipmentService
  ) {}

  ngOnInit(): void {
    this.getShipment();
  }
  getShipment(): void {
    const id = this.route.snapshot.paramMap.get('id');
    console.log(id);
    this.shipmentService
      .getShipment(id)
      .subscribe((shipment) => (this.shipment = shipment));
  }
}

我在服務中的裝運方法是

  getShipment(id: string): Observable<any[]> {
    const shipmentUrl = `${this.url}/${id}`;
    return this.http.get<any[]>(shipmentUrl);
  }

html 組件的發貨信息。 ship.id 或 shipping.name 返回未定義

<div class="shipment">
  {{ shipment }}
</div>

object數據

 {
    "id": "S1000",
    "name": "T-shirts(Summer2018) from Shanghai to Hamburg",
    "cargo": [
      {
        "type": "Fabric",
        "description": "1000 Blue T-shirts",
        "volume": "2"
      },
      {
        "type": "Fabric",
        "description": "2000 Green T-shirts",
        "volume": "3"
      }
    ],
    "mode": "sea",
    "type": "FCL",
    "destination": "Saarbrücker Str. 38, 10405 Berlin",
    "origin": "Shanghai Port",
    "services": [
      {
        "type": "customs"
      }
    ],
    "total": "1000",
    "status": "ACTIVE",
    "userId": "U1000"
  },

您不能直接打印 object,您必須打印要打印的任何值。 如下所示,

如果您收到數組作為響應,請在下面使用

<div class="shipment"  *ngFor="let ship of shipment">
 Name: {{ ship.name }}
 <br>
 Mode: {{ship.mode}}
</div>

否則,像這樣將您的服務方法返回類型數組更改為 object,

getShipment(id: string): Observable<any> {
    const shipmentUrl = `${this.url}/${id}`;
    return this.http.get<any>(shipmentUrl);
  }

和 html 代碼將是這樣的,

<div class="shipment" *ngIf="shipment">
 Name: {{ shipment?.name }}
 <br>
 Mode: {{shipment?.mode}}
</div>

您可以從Angular.io參考此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM