我有一个父函数ngOnInit()
,它从谷歌地图中获取值,如下所示
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()
是与共享服务共享价值的功能,在html页面上我有与父母子女相同的事情
<input id="google_places_ac" [(attr.state)]="state" [(attr.country)]="coutnry" name="google_places_ac" type="text" value="{{city}}" class="form-control" />
我在setValue()
函数
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);
}
这在父母身上运作良好但是孩子没有发生变化,我创建了一个点击功能,它触发了对孩子也有效的改变检测,但是我希望它从父母那里自动启动是否有任何解决方法呢?
答案 0 :(得分:3)
在组件之间共享全局对象时,最好将全局共享服务与Rxjs
observable design pattern
结合使用。以下是代码,您应该根据自己的配置:
首先,您的全局共享服务应如下所示:
import {Injectable} from "angular2/core";
import {Subject} from "rxjs/Subject";
@Injectable()
export class SearchService {
private _searchText = new Subject<string>();
public searchTextStream$ = this._searchText.asObservable();
broadcastTextChange(text:string) {
this._searchText.next(text);
}
}
其次,您将service
注入parent component
...
constructor(private _searchService:SearchService) {
...
第三,添加到您的父组件或更高组件的providers
列表中的服务,因为此服务在订阅组件之间应该是相同的实例,这部分非常重要强>:
providers: [SearchService,...]
然后,如果您想broadcast
进行新的更改,请使用新值调用broadcastTextChange
,如下所示:
...
this._searchService.broadcastTextChange("newTextHere");
...
然后在the child component
内注入相同的service
并订阅它:
this._searchService.searchTextStream$.subscribe(
text => {
// This text is a new text from parent component.
this.localText = text;
//Add your own logic here if you need.
}
)