1

我有一个父函数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()在父组件类中,我在函数上触发 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);
    }

这在父级上运行良好,但在子级上没有发生变化,我创建了一个点击功能,它在子级上触发 changedetection 也可以,但我希望它从父级自动触发有什么解决方法吗?

4

1 回答 1

4

在组件之间共享全局对象时,最好使用全局共享服务结合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);
    }
}

其次,你注入你serviceparent 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.
        }
    )
于 2016-04-03T18:53:01.330 回答