* Angular 2中的ngFor和http请求

时间:2016-11-29 11:13:11

标签: http angular request rendering ngfor

我有一个seguent list-componet

@Component({
    selector: 'my-vote-list',
    template: `<my-vote *ngFor="let question of questions" [question]="question"></my-vote>`
})
export class VoteListComponent implements OnInit {

    constructor(private voteService: VoteService, private authService: AuthService){}

    private votes: any[];

    ngOnInit(){
        this.voteService.keepVotation()
        .subscribe(
            data => {
                this.votes = data;
                console.log(this.votes);
            }, 
            err => console.log(err)
        );
    }
}

当我从我的服务中检索数据时:

import { Injectable, EventEmitter } from "@angular/core";
import { Http, Headers } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Subject }    from 'rxjs/Subject';
import "rxjs/Rx";

import { Vote } from '../insert-vote/vote';

@Injectable()
export class VoteService {

    constructor (private http: Http) {}

    public votations: any[];

    keepVotation(){
        const token = localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : '';
        return this.http.get('http://localhost:3000/vote/votations/' + token)
            .map(response =>{
                const data = response.json().obj;
                let votations: any[] = [];
                for (let i = 0; i < data.length; i++) {
                    let votation = new Vote(data[i].title, data[i].promoter, data[i].theme, data[i].file, null, data[i]._id);
                    votations.push(votation);
                };
                this.votations = votations;
                return votations;
            })
    }
}

它不会将数据绑定到this.vote结果未定义。我在另一个组件中做同样的事情,每件事都有效。 这是我加载的第一个视图 有没有人有任何想法?

0 个答案:

没有答案