Javascript 无法在视图6中显示类属性值
我试图从服务中获取用户位置,并将其显示在组件视图中。我完全可以将位置从服务中获取到组件中。但当我在视图中显示它时,它显示为未定义。 下面是代码 服务:Javascript 无法在视图6中显示类属性值,javascript,angular,Javascript,Angular,我试图从服务中获取用户位置,并将其显示在组件视图中。我完全可以将位置从服务中获取到组件中。但当我在视图中显示它时,它显示为未定义。 下面是代码 服务: enteredLocationName = new Subject<string>(); sendEnteredLocationName(location) { this.enteredLocationName.next(location); } getEnteredLocationName() { return
enteredLocationName = new Subject<string>();
sendEnteredLocationName(location) {
this.enteredLocationName.next(location);
}
getEnteredLocationName() {
return this.enteredLocationName.asObservable();
}
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();
}
}
input [value]="enteredLocation" type="text" class="form-control"
placeholder="Selected Location"
组件视图:
enteredLocationName = new Subject<string>();
sendEnteredLocationName(location) {
this.enteredLocationName.next(location);
}
getEnteredLocationName() {
return this.enteredLocationName.asObservable();
}
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();
}
}
input [value]="enteredLocation" type="text" class="form-control"
placeholder="Selected Location"
当您使用Subject时,它不包含任何值,只要在您更改其值时调用订阅即可。因此,其持久值未定义。
您应该改用BehaviorSubject,它可以保存持久值
enteredLocationName = new BehaviorSubject<string>('');
enteredLocationName=新行为主体(“”);
使用ngModel
绑定,而不是值
与初始阶段一样,value
绑定未定义的值,因此在获取值后,它不会更新值,但ngModel
会更新值
否则,您可以尝试使用async
管道。如果要使用值
<input [value]="enteredLocation | async" type="text" class="form-control"
placeholder="Selected Location">
PS:我不确定使用
async
是否有效。能否尝试使用ngModel
而不是[value]
作为输入属性?问题在于主题。在我将Subject改为Behavior Subject之后,它工作得很好。ngModel也是值得注意的一点。感谢您的帮助。。很高兴您找到了解决方案!:)正如你所说,问题在于主题。在我将Subject改为Behavior Subject之后,它工作得很好。ngModel也是值得注意的一点。谢谢你们的帮助。没问题,如果我的答案对你们有帮助,请把它标记为答案。祝你好运