繁体   English   中英

使用共享服务更改angular2中的检测

[英]change detection in angular2 using shared service

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

这在父母身上运作良好,但是孩子没有发生变化,我创建了一个点击功能,它触发了对孩子也有效的改变检测,但是我希望它从父母那里自动解雇是否有任何解决方法呢?

在组件之间共享全局对象时,最好将全局共享服务与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.
        }
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM