首页 文章

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

提问于
浏览
1

我有一个父函数 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 回答

  • 3

    在组件之间共享全局对象时,最好使用与 Rxjs observable design pattern 结合的全局共享服务 . 这是代码, You should configure it according to yours

    首先,您的全局共享服务应如下所示:

    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 列表或更高组件的服务,因为此服务应该在订阅的组件之间 instanceThis part is very important

    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.
            }
        )
    

相关问题