julio
julio

Reputation: 2937

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)

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...

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

Upvotes: 0

Views: 293

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657038

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

Upvotes: 2

Related Questions