Asridh Kumar
Asridh Kumar

Reputation: 525

Failing to display a class property value in view angular 6

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

Answers (2)

Pardeep Jain
Pardeep Jain

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

dAxx_
dAxx_

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

Related Questions