我的JSON响应(来自ASP.NET核心Web )如下所示:
[
{
"pilot": {
"firstName": "TEST",
"lastName": "LAST",
"assignedFlight": "O_FLIGHT"
}
},
{
"pilot": {
"firstName": "First",
"lastName": "Last",
"assignedFlight": "M_FLIGHT"
}
}
]我的TypeScript接口看起来像:
pilot.ts
export interface Pilot {
firstName: string;
lastName: string;
assignedFlight: string;
}commitment.ts
import { Pilot } from './pilot';
export interface Commitment {
pilot: Pilot;
}在我的commitments.service.ts里
@Injectable({
providedIn: 'root'
})
export class CommitmentsService {
private commitmentsApiUrl = 'http://localhost:55012/commitments';
constructor(private http: HttpClient) { }
getCommitments(): Observable<Commitment[]> {
return this.http.get<Commitment[]>(this.commitmentsApiUrl).pipe(tap(ev => console.log(ev)));
}
}最后,我赞同在我的组件中可观察到的内容:
@Component({
selector: 'app-commitments',
templateUrl: './commitments.component.html',
styleUrls: ['./commitments.component.css']
})
export class CommitmentsComponent implements OnInit {
commitments: Commitment[];
constructor(private commitmentsService: CommitmentsService) { }
ngOnInit(): void {
this.commitmentsService.getCommitments().subscribe(commitments => this.commitments = commitments);
console.log(this.commitments); /* Undefined here??? */
}
}对于我的生活,我不明白为什么当涉及嵌套接口时没有映射JSON。组件中的this.commitments显示undefined。我已经通过JSON验证器/linter运行了JSON,它表明它是有效的。我知道答案很简单,我对此视而不见。有什么想法吗?谢谢!
发布于 2020-06-18 12:53:39
界面看起来很好。this.commitments是异步分配的。当您执行控制台日志时,变量this.commitments仍未定义。您需要将console.log()移动到订阅中。
this.commitmentsService.getCommitments().subscribe(
commitments => {
this.commitments = commitments;
console.log(this.commitments);
},
error => {
// always good practice to handle HTTP errors
}
);有关如何访问异步数据here的更多详细信息。
发布于 2020-06-18 12:56:20
除非您的组件中绝对必须有this.commitments,否则不要。它会使事情变得更复杂,使用异步管道代替:
// component
@Component({
selector: 'app-commitments',
templateUrl: './commitments.component.html',
styleUrls: ['./commitments.component.css']
})
export class CommitmentsComponent implements OnInit {
commitments$ = this.commimentsService.getCommitments();
constructor(private commitmentsService: CommitmentsService) { }
}
//template
<some-other-component [commitments]="commitments$ | async"></some-other-component>所谓“让事情变得更复杂”,我的意思是说,您有很多事情需要自己考虑--管理订阅,确保this.commitments在从组件内部访问它时是最新的。
我开发的应用程序中,每个组件都创建了大量实例变量,这完全是为了上面编写的模式。它变得比你想象的要快得多。
https://stackoverflow.com/questions/62450377
复制相似问题