我有一个父函数 ngOnInit()
从谷歌 Map 获取值如下
instance.input = document.getElementById('google_places_ac');
autocomplete = new google.maps.places.Autocomplete(instance.input, { types: ['(cities)']});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
instance.setValue(place.address_components[3].long_name, place.address_components[2].long_name, place.address_components[1].long_name);
});
setValue()
是与共享服务共享 Value 的功能,在html页面上我跟父母和孩子一样 <input id="google_places_ac" [(attr.state)]="state" [(attr.country)]="coutnry" name="google_places_ac" type="text" value="{{city}}" class="form-control" />
在父组件类中,我在 setValue()
函数上触发changedetection
setValue(a, b, c) {
this.coutnry = a;
this.state = b;
this.city = c;
this.sharedService.country = this.coutnry;
this.sharedService.city = this.city;
this.sharedService.state = this.state;
this.cdr.detectChanges();
// console.log(this.coutnry, this.state, this.city);
}
这在父母身上运作良好,但是孩子没有发生变化,我创建了一个点击功能,它触发了孩子的变化检测也有效,但我希望它从父母自动解雇是否有任何解决方法呢?
1 回答
在组件之间共享全局对象时,最好使用与
Rxjs
observable design pattern
结合的全局共享服务 . 这是代码, You should configure it according to yours :首先,您的全局共享服务应如下所示:
其次,你将
service
注入你的parent component
第三,添加到父组件的
providers
列表或更高组件的服务,因为此服务应该在订阅的组件之间 instance , This part is very important :然后,当您想要
broadcast
新更改时,使用新值调用broadcastTextChange
,如下所示:然后在
the child component
内注入相同的service
并订阅它: