使用共享服务在 Angular2 中进行更改检测

Iro*_*sun 1 angular2-changedetection angular

我有一个父函数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);

        });
Run Code Online (Sandbox Code Playgroud)

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);
    }
Run Code Online (Sandbox Code Playgroud)

这在父级上运行良好,但在子级上没有发生更改,我创建了一个单击函数,该函数在子级上触发更改检测,这也有效,但我希望它从父级自动触发,有什么解决方法吗?

Tur*_*tan 5

当涉及到在组件之间共享全局对象时,最好使用全局共享服务与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);
    }
}
Run Code Online (Sandbox Code Playgroud)

其次,你将你的注入service到你的parent component

...
constructor(private _searchService:SearchService) {
...
Run Code Online (Sandbox Code Playgroud)

providers第三,将服务添加到您的父组件或更高组件的列表中,因为该服务应该在订阅的组件之间具有相同的实例这部分非常重要

providers: [SearchService,...]
Run Code Online (Sandbox Code Playgroud)

然后,当您想要进行broadcast新更改时,您可以broadcastTextChange使用新值进行调用,如下所示:

...
this._searchService.broadcastTextChange("newTextHere");
...
Run Code Online (Sandbox Code Playgroud)

然后在你的内部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.
        }
    )
Run Code Online (Sandbox Code Playgroud)