【问题标题】:How to show backend response in drop down如何在下拉列表中显示后端响应
【发布时间】:2021-02-09 03:15:11
【问题描述】:

目前我正在硬编码我的下拉列表选项,因为后端还没有准备好,我是这样做的

<mat-option *ngFor="let notificationType of notificationTypes"
[value]="notificationType.value">{{notificationType.content}}
</mat-option>

  //I hardcoded like this for now
  notificationTypes = [{ value: 1, content: "Broadcast" }, { value: 2, content: "Alert" }, { value: 3, content: "Release" }];


ngOnInit(): void {

// but now the backend get call for notificationType is ready

   this.notificationService.getNotificationTypes().subscribe((response: any) => {
      console.log("NOTIFICATION TYPES", response);
    })
  }

但现在后端获取 notificationType 已准备就绪,但我不确定如何将响应值分配给 notificationTypes 变量,因此如果我能得到任何建议或帮助将不胜感激。

我猜 id = value 和 content = message。

【问题讨论】:

    标签: html angular database typescript api


    【解决方案1】:
        // define the variable which will hold the response    
        notificationTypes = [];    
        
        ngOnInit(): void {    
        
           this.notificationService.getNotificationTypes().subscribe((response: any) => {    
           // assign the response to the defined variable    
              this.notificationTypes = response;    
            });    
          } 
    
    // The binding has to correlate with the response from the server.
    // If not, you will get an error
    
    <mat-option *ngFor="let notificationType of notificationTypes"
    // It is a common practice for the value to hold the ID of the Item
    [value]="notificationType?.id" [matTooltip]="notificationType?.description">{{notificationType?.name}}
    </mat-option>
    

    【讨论】:

      【解决方案2】:

      您可以使用 id 作为值,名称作为内容,描述作为工具提示:

      <mat-option *ngFor="let notificationType of notificationTypes"
      [value]="notificationType.id" [matTooltip]="notificationType.description">{{notificationType.name}}
      </mat-option>
      
      notificationTypes =[]
      
            ngOnInit(): void {
                this.notificationService.getNotificationTypes().subscribe((response: any) => {
                  this.notificationTypes = response
                });
              }
      

      【讨论】:

        【解决方案3】:

        您应该等待响应并分配它。这有效:

        ngOnInit(): void {
          this.notificationService.getNotificationTypes().subscribe((response: any) => {
            this.notificationTypes = response.map(obj => {
               return { value: obj.id, content: obj.message }; 
            };
          });
        }
        

        【讨论】:

          猜你喜欢
          • 2019-12-02
          • 2016-10-15
          • 1970-01-01
          • 2020-06-24
          • 2016-01-29
          • 2019-05-05
          • 1970-01-01
          • 2018-02-23
          • 2011-09-24
          相关资源
          最近更新 更多