Reputation: 525
I am trying to get user location from a service and display it in a component view.I could very well get the location from service into component.But when i display it in view it displays as undefined. Below is the code.
Service:
enteredLocationName = new Subject<string>();
sendEnteredLocationName(location) {
this.enteredLocationName.next(location);
}
getEnteredLocationName() {
return this.enteredLocationName.asObservable();
}
Component-TS:
export class RestaurantSearchComponent implements OnInit {
enteredLocationName: Subscription;
enteredLocation:string;
constructor(private shareDataService: ShareDataService) { }
ngOnInit() {
this.getEnteredLocationName();
}
getEnteredLocationName(){
this.enteredLocationName =
this.shareDataService.getEnteredLocationName().subscribe(resp => {
this.enteredLocation = resp;
});
}
ngOnDestroy() {
this.enteredLocationName.unsubscribe();
}
}
Component-View:
input [value]="enteredLocation" type="text" class="form-control"
placeholder="Selected Location"
Upvotes: 0
Views: 99
Reputation: 86740
Bind with ngModel
instead of value
.
As in the initial stage value
binds the value which is undefined so after getting value it will not update the value but ngModel
does.
Else you can try with async
pipe. if you want to use value.
<input [value]="enteredLocation | async" type="text" class="form-control"
placeholder="Selected Location">
PS: I am not sure with async
will works or not.
Upvotes: 1
Reputation: 2290
When you are using Subject, it doesnt hold any values, its just invoke the subscription when ever you change its value. hence, its persistent value is undefined.
You should use BehaviorSubject instead, which can hold persistent value.
enteredLocationName = new BehaviorSubject<string>('');
Upvotes: 0