Search code examples
angularangular2-services

angular2 It appears only as an object object on the screen


On the view screen, you can not get the desired json key value. I tried the following. board.component.html

board.component.html

{{board.title}} > [Object Object],

{{board?.title}} > Nothing ,

{{board | Json}} > [{ "title" : "AAAAAA", "cont" : "AAAA1234", "date" : "2017-03-03", "hit" : "5" }]

board.component.ts

@Component({
    selector : 'board',
    templateUrl : './board.component.html'
})

export class boardComponent implements OnInit{
    pageTitle : string = 'board';
    errorMessage : string;
    board : Board[];

    constructor(private _boardService : BoardService){}

    ngOnInit() : void {
        this._boardService.getBoard()
            .subscribe(
                boards => this.board = boards, 
                error => this.errorMessage = <any> error
            );
        console.log('board In OnInit');
    }
}

board.service.ts

@Injectable()
export class BoardService{
    private _boardUrl = '/src/api/board/board.json';

    constructor(private _http : Http){}

    getBoard() : Observable<Board[]>{
        return this._http.get(this._boardUrl)
            .map((response : Response) => <Board[]> response.json())
            .do(data => console.log('Board : ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(error : Response){
        return Observable.throw(error.json().error || 'Server error');
    }
}

Solution

  • You should use *ngFor since board is an array. Or if you want to access the first element you can do this,

    {{board[0]?.title}}