簡體   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