繁体   English   中英

Angular - 将下拉列表或 select 绑定到 API(数据库)

[英]Angular - Bind Dropdown or select to API (database)

我在一个带有 Angular 和后端的项目中。

如果我在 ts 文件中输入一个列表:

this.towns = [{
       code: '1',
       label: 'Paris'
   },
   {
       code: '0',
       label: 'Vancouver'
   }
 ];

我可以在我的 html 中显示它们,但如果我尝试连接到数据库则不能:

<select  class="selectpicker dropdown mt-4 ml-3" id="town">
   <option *ngFor="let town of towns" [value]="town.id">{{town.name}}</option>
</select>

在我的 ts 文件中,我尝试了:

export class TestComponent implements OnInit {
 
  form: FormGroup;
  towns: { id: number, name: string }[];
 
  constructor(
    private http: HttpClient
  ) { }
 
  towns: Town[];
  apiUrl = 'https://localhost:8000/api/';
 
  ngOnInit(): void {
    this.form = new FormGroup({
      town: new FormControl()
    });
    this.getTown();
  }
 
  onClickTown(): Observable<any> {
    console.log(this.form)
    return this.http.get(this.apiUrl + 'towns')
  }
 
  getTown() {
    this.http.get<any[]>(this.apiUrl + 'towns')
      .subscribe(data => {
        this.towns = data;
        console.log(data)
      });
  }
 
  postData() {
    console.log("data");
    this.http.post<any[]>(this.apiUrl, {}).
      subscribe(
        (data: any[]) => {
          // console.log(data);
        }
      )
  }

我忘了一步吗? 谢谢

这是因为未检测到更改。 您可以尝试重新初始化 towns 数组,以便 Angular 检测到更改。

getTown() {
  this.http.get<any[]>(this.apiUrl + 'towns')
    .subscribe(data => {
      /* reinitialize the towns array */
      this.towns = [];
      /****/
      this.towns = data;
      console.log(data)
    });
}

试试下面的代码。

我使用async pipe 进行迭代。 (请注意,您应该为此返回 Observable)我还使用ngValue属性绑定到表单

HTML

<select formControlName="town">
  <option *ngFor="let town of towns | async" [ngValue]="town">{{town.name}}</option>
</select>

TS接口

exprot interface Town{
  id:number;
  name:string;
}

TS 组件

export class TestComponent implements OnInit {

  form: FormGroup;
  towns:Observable<Town[]>;
  apiUrl:string = 'https://localhost:8000/api/';

  constructor(private http: HttpClient) { }

  ngOnInit(): void {        
    this.towns = this.http.get<Town[]>(this.apiUrl + 'towns');        
    this.form = new FormGroup({
      town: new FormControl()
    });
  }

我改变了我的 getTown function 来解决它,所以我的 html:

  getTown() {
    this.townsObs = this.http.get<any[]>(this.apiUrl + 'towns').subscribe(data => {
        this.towns = data['hydra:member'];
        console.log(data['hydra:member'])
      });
  }

谢谢大家

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM