代码之家  ›  专栏  ›  技术社区  ›  evolmind

Angular 2:如何使用我的服务从json文件中填充下拉列表?

  •  1
  • evolmind  · 技术社区  · 6 年前

    我有一项服务:

    @Injectable()
    export class LostFoundEditService {
        public lostForm: FormGroup;
        public countries: any[] = [];
        private countriesUrl = 'assets/countries.json';
    
        constructor(private http: HttpClient) { }
    
        init() {
            this.initForm();
    
            this.http.get(this.countriesUrl).subscribe(data => {
                this.countries = this.countries.concat(data['countries']);
            },
            (err: HttpErrorResponse) => {
                console.log(err.message);
            });
        }
    
        private initForm() {
            this.lostForm = new FormGroup({
                'title': new FormControl('', Validators.required),
                'description': new FormControl('', Validators.required),
                'country': new FormControl('', Validators.required),
                'state': new FormControl('', Validators.required),
                'city': new FormControl('', Validators.required),
                'zipCode': new FormControl(''),
                'street': new FormControl('')
            });
        }
    }
    

    以及使用此服务的类:

    @Component({
      selector: 'app-lost-edit',
      templateUrl: './lost-edit.component.html',
      styleUrls: ['./lost-edit.component.css']
    })
    export class LostEditComponent implements OnInit {
      lostForm: FormGroup;
      countries: any[] = [];
      states: any[] = [];
      cities: any[] = [];
    
      constructor(
        private http: HttpClient,
        private lostFoundEditService: LostFoundEditService) { }
    
      ngOnInit() {
        this.lostFoundEditService.init();
        this.lostForm = this.lostFoundEditService.lostForm;
        this.countries = this.lostFoundEditService.countries;
      }
    
      onCancel() {
      }
    

    }

    此外,我还有与该类关联的模板:

    (...)
                      <select
                        id="country"
                        formControlName="country"
                        class="form-control">
                        <option value="">Countries</option>
                        <option *ngFor="let country of countries" value="{{country['id']}}">{{country['name']}}</option>
                      </select>
                    </div>
                </div>
              </div>
              (...)
    

    我的问题是:如何等待subscribe方法的结束(在 init() 属于 LostFoundEditService )输入json文件的所有国家/地区 countries 的数组 LostEditComponent 。目前下拉列表中没有显示任何内容。。。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Molik Miah    6 年前

    你可以试试这个。

    我在这里所做的是将countries属性从数组更改为行为主题,这意味着您的组件可以订阅此属性。我们可以使用模板中的异步管道进行订阅,在角度世界中,该管道称为订阅。

    在您的服务中,当我们通过subscribe完成数据获取后,您可以通过这样做来设置值。国家/地区。下一步(数据[‘国家’])。

    服务:

    import {BehaviorSubject} from 'rxjs/BehaviorSubject';
    
    @Injectable()
    export class LostFoundEditService {
        public lostForm: FormGroup;
        public countries: Subject = new BehaviorSubject<Array<any>>(null);
        private countriesUrl = 'assets/countries.json';
    
        constructor(private http: HttpClient) { }
    
        init() {
            this.initForm();
    
            this.http.get(this.countriesUrl).subscribe(data => {
                this.countries.next(this.countries.concat(data['countries']));
            },
            (err: HttpErrorResponse) => {
                console.log(err.message);
            });
        }
    
        private initForm() {
            this.lostForm = new FormGroup({
                'title': new FormControl('', Validators.required),
                'description': new FormControl('', Validators.required),
                'country': new FormControl('', Validators.required),
                'state': new FormControl('', Validators.required),
                'city': new FormControl('', Validators.required),
                'zipCode': new FormControl(''),
                'street': new FormControl('')
            });
        }
    }
    

    组件:

    @Component({
      selector: 'app-lost-edit',
      templateUrl: './lost-edit.component.html',
      styleUrls: ['./lost-edit.component.css']
    })
    export class LostEditComponent implements OnInit {
      lostForm: FormGroup;
      countries;
      states: any[] = [];
      cities: any[] = [];
    
      constructor(
        private http: HttpClient,
        private lostFoundEditService: LostFoundEditService) { }
    
      ngOnInit() {
        this.lostFoundEditService.init();
        this.lostForm = this.lostFoundEditService.lostForm;
        this.countries = this.lostFoundEditService.countries;
      }
    
      onCancel() {
      }
    

    }

    模板:

    (...)
                      <select
                        id="country"
                        formControlName="country"
                        class="form-control">
                        <option value="">Countries</option>
                        <option *ngFor="let country of countries | async" value="{{country['id']}}">{{country['name']}}</option>
                      </select>
                    </div>
                </div>
              </div>
              (...)