Angular中如何通过下拉框选中的id属性值获取对应对象的name属性
实现方案
现有代码核心问题:
- 接口返回的是Book数组,现有代码类型定义为单个Book,类型不匹配
- 没有对返回的全量图书数据按选中id做过滤匹配
- 模板渲染直接输出对象,未取对应的name属性
步骤1:修正service.ts的类型定义
你的book-details.json返回的是数组,所以要把返回值类型从Observable<Book>改成Observable<Book[]>:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Book } from './book'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class GetService { constructor(private http:HttpClient) { } getDetails():Observable<Book[]>{ return this.http.get<Book[]>("assets/book-details.json") } }
步骤2:修改app.component.ts的逻辑
调整变量定义,新增选中图书存储变量,在拿到全量数据后按selectedId匹配:
import { Component, OnInit } from '@angular/core'; import { Book } from './book'; import { GetService } from './get.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(){} constructor(private service:GetService,){} // 存储所有图书列表 bookList!: Book[]; // 改成基础类型number,避免包装类类型匹配问题 selectedId!: number // 存储匹配到的选中图书 selectedBook?: Book; selectedObj: number[]=[1,2,3,4] details(){ this.service.getDetails().subscribe(bookList=> { this.bookList = bookList; // 按选中的id匹配对应图书 this.selectedBook = this.bookList.find(item => item.id === this.selectedId); }) } }
步骤3:调整app.component.html模板渲染逻辑
直接取选中图书的name属性展示,加可选链避免空值报错:
<select [(ngModel)]="selectedId" (change)="details()"> <option *ngFor="let b of selectedObj" [value]="b">{{b}}</option> </select> <p>{{selectedBook?.name}}</p>
额外注意事项
如果运行时ngModel报错,需要在app.module.ts中导入FormsModule和HttpClientModule:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
内容的提问来源于stack exchange,提问作者wizard lol
相关产品推荐
相关产品推荐

