[英]Angular2 Data binding with data from service
I have this component 我有这个组件
@Component({
templateUrl: './app/component/template/actualstate.template.html',
styleUrls: ['./app/component/style/actualstate.style.css'],
pipes: [MomentPipe, CapitalizePipe]
})
export class ActualStateComponent implements OnInit {
public room: Room;
constructor(private roomService: RoomService) {
roomService.roomSelected$.subscribe(room => this.onRoomSelected(room));
}
onRoomSelected(room: Room) {
this.room = room;
console.log("room", room);
}
}
and this other component 和其他组件
@Component({
templateUrl: './src/admin/template/admin.template.html',
styleUrls: ['./src/admin/style/admin.style.css'],
providers: [UserService]
})
export class AdminComponent{
constructor ( private roomService: RoomService) {
}
onClick () {
this.roomService.selectRoom("","");
this.router.navigate(['ActualState']);
}
}
}
, this service : ,此服务:
@Injectable()
export class RoomService {
private route_room = "public/mock/room.json";
public roomSelected$: EventEmitter<Room>;
constructor (private http: Http) {
this.roomSelected$ = new EventEmitter();
}
public selectRoom (subdomain: string, id: string) {
// pick the right room
let room = ...
this.roomSelected$.emit(room);
}
private handleError (error: Response) {
return Observable.throw(error.json().error || 'Server error');
}
}
And this template : 和这个模板:
<div class="actual-state" *ngIf="room">
<h3>Salle {{ room.name }}
</h3>
</div>
The purpose is : Admin component (user click on some button) -> Listener OnClick calls a method on service roomService -> roomService emit an event (that is public) -> appComponent listen to this event (.subscribe) 目的是:管理组件(用户单击某些按钮)->侦听器OnClick在service roomService上调用方法-> roomService发出事件(是公共的)-> appComponent侦听此事件(.subscribe)
I have no clue why this is not working. 我不知道为什么这不起作用。 The
<h3>
is never showing .. even though the console.log(room) display something in the console... <h3>
从不显示..即使console.log(room)在控制台中显示了某些内容...
How does this data binding working ? 此数据绑定如何工作? Because it just looks like data are not two-way bound ...
因为它看起来像数据不是双向绑定的 ...
EDIT : i understood the problem, it was related to the routing i made. 编辑:我了解问题,这与我所做的路由有关。 in fact i did'nt understand the fact that component of a route is destroyed when you change the route
实际上,我不了解以下事实:更改路线时会破坏路线的组成部分
I guess you need to subscribe 我想你需要订阅
return this.http.get(this.route_room)
.map(res => res.json())
.do(data => {
this.roomSelected$.emit(data);
})
.subscribe(value => {})
.catch(this.handleError);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.