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

Angular 2 : how to populate a dropdown list from a json file with my service?

我有服务:

@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('')
        });
    }
}

还有一个 class 使用此服务:

@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() {
  }

}

我还有与之关联的模板 class :

(...)
                  <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>
          (...)

我的问题是:如何等待订阅方法结束(在 LostFoundEditServiceinit() 中)以在 [=17= 中输入 json 文件的所有国家/地区] LostEditComponent 数组。下拉列表中暂时没有任何内容...

你可以试试这个。

我在这里所做的是将国家 属性 从数组更改为 BehaviourSubject,这意味着您的组件可以订阅此 属性。我们可以通过在模板中使用异步管道进行订阅,在 angular 世界中调用订阅。

在您的服务中,当我们通过订阅完成获取数据后,您可以通过执行 this.countries.next(data['countries']).

来设置值

服务:

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>
          (...)