首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度插值无法访问对象

角度插值无法访问对象
EN

Stack Overflow用户
提问于 2020-11-19 02:26:16
回答 1查看 98关注 0票数 0

这是一个Angular项目。我需要访问模板中已存在于组件中的对象。当我通过控制台记录该对象时,我看到了它,但当我试图访问它时,什么也没有发生。请注意,我尝试做的是按特定名称过滤对象。

代码语言:javascript
复制
import { Component, OnInit, Input } from '@angular/core';
import {SwapiService} from "../../models/swapi.service";
import {BehaviorSubject, Subject} from "rxjs";
import {Pilot, Starship} from "../../models/starship";
import {MatTableDataSource} from "@angular/material/table";
import {ActivatedRoute} from "@angular/router";


@Component({
  selector: 'app-starship',
  templateUrl: './starship.component.html',
  styleUrls: ['./starship.component.css']
})
export class StarshipComponent implements OnInit {
  public starship: Starship;
  public name: string;
  public crew: number;
  public pilots: Pilot[];
  public index;
 


  constructor(private swapi: SwapiService,
              private route: ActivatedRoute) {
    this.name = this.route.snapshot.paramMap.get('name');
     }


  loadStarship(): void {
    this.swapi.getStarshipList().subscribe(
      res => {
        this.starship = JSON.parse(JSON.stringify(res));
        this.swapi.setData(res)
        this.crew = this.starship.crew;
        console.log(this.crew);
        console.log(this.starship[0]);

        console.log(this.name);

        console.log(res);
      }
    )
  }



  ngOnInit(){
    this.loadStarship();
    
  }


}

我的模板

代码语言:javascript
复制
<p *ngIf="starship">{{starship.crew}}</p>
<p>{{starship.name}}</p>

请注意,由于激活了路由,starship.name可以工作,但crew不能。我已经尝试过EVERything了!!

我在Json中的回答是:

代码语言:javascript
复制
Angular is running in development mode. Call enableProdMode() to enable production mode.
main.js:42 undefined
main.js:43 {name: "CR90 corvette", model: "CR90 corvette", manufacturer: "Corellian Engineering Corporation", cost_in_credits: "3500000", length: "150", …}MGLT: "60"cargo_capacity: "3000000"consumables: "1 year"cost_in_credits: "3500000"created: "2014-12-10T14:20:33.369000Z"crew: "30-165"edited: "2014-12-20T21:23:49.867000Z"films: (3) ["http://swapi.dev/api/films/1/", "http://swapi.dev/api/films/3/", "http://swapi.dev/api/films/6/"]hyperdrive_rating: "2.0"length: "150"manufacturer: "Corellian Engineering Corporation"max_atmosphering_speed: "950"model: "CR90 corvette"name: "CR90 corvette"passengers: "600"pilots: []starship_class: "corvette"url: "http://swapi.dev/api/starships/2/"__proto__: Object
main.js:44 Star Destroyer
main.js:45 (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
EN

回答 1

Stack Overflow用户

发布于 2020-11-19 02:31:37

API响应是一组星际飞船,而不是一艘单独的飞船。在这里this.starship = JSON.parse(JSON.stringify(res))你把整个舰队放在你的starship变量中,因此starship.name将是未定义的。

将赋值更改为this.starship = res[0],您将看到名称。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64899096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档