你可以试试这个。
我在这里所做的是将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>
(...)