这是一个Angular项目。我需要访问模板中已存在于组件中的对象。当我通过控制台记录该对象时,我看到了它,但当我试图访问它时,什么也没有发生。请注意,我尝试做的是按特定名称过滤对象。
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();
}
}我的模板
<p *ngIf="starship">{{starship.crew}}</p>
<p>{{starship.name}}</p>请注意,由于激活了路由,starship.name可以工作,但crew不能。我已经尝试过EVERything了!!
我在Json中的回答是:
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) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]发布于 2020-11-19 02:31:37
API响应是一组星际飞船,而不是一艘单独的飞船。在这里this.starship = JSON.parse(JSON.stringify(res))你把整个舰队放在你的starship变量中,因此starship.name将是未定义的。
将赋值更改为this.starship = res[0],您将看到名称。
https://stackoverflow.com/questions/64899096
复制相似问题