首次以angular2

时间:2016-04-04 09:53:46

标签: angular angular2-changedetection

我正在尝试将谷歌地图值从父组件转移到我为其创建共享服务的路由组件,如下所示

import {Injectable}     from 'angular2/core';
import {Subject} from "rxjs/Subject";
@Injectable()
export class SearchService {

    private addressmap= new Subject<Sharedcomponent >();

    public searchaddressStream$ = this.addressmap.asObservable();

    broadcastaddressChange(address: Sharedcomponent ) {
        this.addressmap.next(address);
    }
}
export class Sharedcomponent {
    country: string;
    state: string;
    city: string;  
    street: string;
}
来自父母的

我在价值变化上广播这个地址,并通过订阅它来接收它,并且只有在子页面用父项呈现时才能正常工作。 如果父项首先被渲染,那么我通过路由调用子视图然后它不会在页面呈现时显示数据,只有当我更改父项中的值时才会显示。子视图正在订阅服务,但在呈现时不会获取数据。 如果您需要更多解释或父母或视图中的代码,请告知我们。希望有人可以帮助我。

更新

这是更新,因此您可以了解我的问题 它是我的应用程序组件,我从谷歌地图api

获取值
declare var google: any;

@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES, ProductComponent],
    providers: [ SearchService]
})


export class AppComponent  {

    constructor(private _http: geoService, private sharedService: SearchService, private cdr: ChangeDetectorRef) {



    }
    ngOnChanges() {
        this.sharedService.broadcastTextChange(this.street);
        this.cdr.detectChanges();
    }
    public maps: geoResult;
    public cat_error: Boolean = false;
    public xml_Latitude :any;
    public xml_Lang: any;
    public city: string;
    public state: string;
    public coutnry: string;
   public street= new SharedService;
    public input: any;
    public autocomplete: any;

    ngOnInit() {
       var instance = this,
       autocomplete;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(res=> {
                instance._http.getPlaces(res.coords.latitude, res.coords.longitude).subscribe(
                    data=> {
                        instance.maps = data;
                        console.log(instance.maps);
                        var result = instance.maps.status;
                        var result2 = instance.maps.results;
                        if (result != "undefined" || "" || null) {

                            instance.setValue(result2[0].address_components[6].long_name, result2[0].address_components[5].long_name, result2[0].address_components[4].long_name);
                        }

                    });
            });
        }
        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(); console.log(place);
            if (place.address_components[3] != undefined ) {
                instance.setValue(place.address_components[3].long_name, place.address_components[2].long_name, place.address_components[1].long_name);
            } else
            {
                instance.setValue(place.address_components[2].long_name, place.address_components[1].long_name, place.address_components[0].long_name);
            }
        });



    }


    setValue(a, b, c) {

        this.street.country = a;
        this.street.state = b;
        this.street.city = c;
        this.sharedService.broadcastTextChange(this.street);

    }


}

稍后我有一个获得此值的子视图

  ngOnInit() {


        this.getNewProduct();
        this.getlocation();


   }
    getlocation() {
        this.shared.searchTextStream$.subscribe(
            text => {
                this.street = text;
                this.country = this.street.country;
                this.state = this.street.state;
                this.city = this.street.city
                console.log(this.country, this.state, this.city);
            }, error=> { console.log(<any>error);}
        );
    }



    getNewProduct() {

        this._productService.selectproduct(0)
            .subscribe(
            product  => {
                this.model = product;

                this.isloading = false;
            console.log(this.model)
            },
            error => this.errorMessage = <any>error);

    }

}

但是我在渲染此视图时没有得到地理定位,如果我在父文本框中更改了值,那么它会在视图中更新

2 个答案:

答案 0 :(得分:1)

如果您想收听上一次广播,即使尚未订阅,您也需要使用BehaviorSubject代替Subject。在这种情况下,即使您在广播后订阅,也会获得最后一次更新。 这是您目前的情况 此代码来自Github

中的RxJS存储库

BehaviorSubject仅为您提供最后一个值。如果您需要最后10或2个值,请改用ReplaySubject

    /*
 * BehaviorSubject
 *
 * Subject that remembers the last (or initial) value
 */

var xs = new Rx.BehaviorSubject()
xs.subscribe(logAllObserver('BehaviorSubject'))
//=> BehaviorSubject - Value: undefined

var xs = new Rx.BehaviorSubject('default')
xs.subscribe(logAllObserver('BehaviorSubject'))
//=> BehaviorSubject - Value: default

var xs = new Rx.BehaviorSubject('default')
xs.onNext('new one')
xs.subscribe(logAllObserver('BehaviorSubject'))
//=> BehaviorSubject - Value: new one

答案 1 :(得分:0)

import {Injectable,EventEmitter}     from 'angular2/core';
import {Subject} from "rxjs/Subject";
@Injectable()
export class SearchService {

   searchaddressStream$:EventEmitter<Sharedcomponent> = new EventEmitter();

    broadcastaddressChange(address: Sharedcomponent ) {
        this.searchaddressStream$.emit(address);
    }
}
ngOnInit() {
        this.getNewProduct();
        // this.getlocation();
}
ngViewAfterInit()
{
   this.getlocation();
}