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

时间:2018-03-08 14:08:03

标签: angular typescript service dropdown populate

我有服务:

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

我的问题是:如何等待订阅方法的结束(在init()的{​​{1}}中)让json文件的所有国家/地区输入LostFoundEditService数组{{1} }}。暂时没有任何内容出现在下拉列表中......

1 个答案:

答案 0 :(得分:1)

你可以试试这个。

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

在您的服务中,当我们通过订阅完成数据获取后,您可以通过执行this.countries.next(数据[&#39;国家&#39;])来设置值。

服务:

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