radio-group 改变值

radio-group changing value

我正在尝试使用 ionic 4 和 angular 制作天气应用程序。我有多个城市,所以我想使用无线电组通过坐标值更改城市。我的问题是当 运行 我的应用程序没有从数据 json 得到任何结果!我得到了 undefined 。即使检查也不起作用,所以我必须检查手册

广播组:

<ion-list>
  <ion-radio-group [(ngModel)]="cities">
    <ion-list-header>
    <ion-label>Name</ion-label>
  </ion-list-header>

  <ion-item>
    <ion-label>Muscat</ion-label>
    <ion-radio slot="start" value="26.2105,56.244" checked></ion-radio>
  </ion-item>

  <ion-item>
    <ion-label>Dubia</ion-label>
    <ion-radio slot="start" value="26.161722,56.23672"></ion-radio>
  </ion-item>

  </ion-radio-group>
</ion-list>

代码:

export class Tab1Page {
  weather:any;
  cities: string;

  constructor(private https: HttpClient) {
    this.test()
  }

  onCitiesChanged(data){
    console.log(data.detail.value);
  }

  async test (){
    this.https.get('weather/'+this.cities+'.json')
      .subscribe(data => {
        this.weather = data
    })
  }
}

url 结果控制台 weather/undefined.json

documentation 开始,您可以使用 ionChange 事件,也可以使用 ngModel。如果要在分配或更改时使用选定的 cities 值,则需要使用 ionChange 事件。请参阅下面的代码,该代码在值更改时进行 http 调用。

关于 ionChange

的注释

当您订阅 ionChange 时,该方法会在首次初始化时触发。您不必在 component/typescript 文件中设置其他值。你不应该在构造函数中进行任何调用 and 在这种情况下没有必要,因为一旦设置了值就会触发方法回调,这发生在 html 呈现为 html 正在使用 checked 属性分配初始选择。

代码

Stackblitz

template.html

<ion-list>
    <ion-radio-group (ionChange)="onCitiesChanged($event)" [(ngModel)]="cities">
        <ion-list-header>
            <ion-label>Name</ion-label>
        </ion-list-header>

        <ion-item>
            <ion-label>Muscat</ion-label>
            <ion-radio slot="start" value="26.2105,56.244" checked></ion-radio>
        </ion-item>

        <ion-item>
            <ion-label>Dubia</ion-label>
            <ion-radio slot="start" value="26.161722,56.23672"></ion-radio>
        </ion-item>
    </ion-radio-group>
</ion-list>

component.ts

constructor(private https: HttpClient) {/* nothing else */}

cities: string;
onCitiesChanged(data){
    this.https.get('weather/'+this.cities+'.json')
      .subscribe(data => this.weather = data);
}

您正在构造函数中调用 test(),不推荐这样做。此外,您还没有为 cities 设置初始值,因此它应该是 undefined.

此外,不要使用checked,将初始值设置为ngModel,如:

cities = '26.2105,56.244'

checked 在这里没有效果,因为 citiesundefined.

当用户选择一个选项时有一个点击事件或什么的,然后调用test。这是一个选项,或者至少在 OnInit 中调用它。我坚信任何不需要在 constructor 中调用的东西都不应该。我们有 OnInit 就是为了这个目的! :)