Angular2数据绑定来自服务的数据

时间:2016-02-22 14:54:06

标签: dependency-injection angular 2-way-object-databinding angular2-template angular2-services

我有这个组件

@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);
    }
}

和其他组件

@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']);
        }
    }
}

,这项服务:

@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');
    }
}

这个模板:

<div class="actual-state" *ngIf="room">
<h3>Salle {{ room.name }}
</h3>
</div>

目的是: 管理组件(用户点击某个按钮)      - &GT;监听器OnClick调用服务roomService上的方法            - &GT; roomService发出一个事件(即公共的)                 - &GT; appComponent听这个事件(.subscribe)

我不知道为什么这不起作用。即使console.log(会议室)在控制台中显示某些内容,<h3>也永远不会显示..

此数据绑定如何工作? 因为它看起来只是数据不是双向绑定 ...

编辑:我理解这个问题,它与我所做的路由有关。 实际上我并不理解当你改变路线时路线的组成部分被破坏的事实

1 个答案:

答案 0 :(得分:2)

我猜您需要订阅

return this.http.get(this.route_room)
                    .map(res => res.json())
                    .do(data => {
                        this.roomSelected$.emit(data);
                    })
                    .subscribe(value => {})
                    .catch(this.handleError);