簡體   English   中英

Angular2服務中的地圖回調函數

[英]Callback to map function in Angular2 service

在我的service.ts文件中,我有一個函數( getQuestions ),該函數調用返回JSON的HTTP服務。 使用此返回的JSON( data ),我想調用另一個函數( buildQuestions ),以便將buildQuestions的結果返回到getQuestions 我如何調用函數以返回buildQuestions的結果或保證,在getQuestions返回buildQuestions的結果時已定義該結果。

data:any;
questions : QuestionBase<any>[] = [];

getQuestions() {
    let result = this.http.get(this.questionUrl)
        .map(res => res.json())
        .map(data => {
            this.data = data;
            return this.buildQuestions(data);
    });
    return result; //should actually return "this.buildQuestions(data)" (or "this.questions.sort((a, b) => a.order - b.order);")
}

buildQuestions(data){
    for (let key in data) {
        //push Objects in this.questions array
    }
    return this.questions.sort((a, b) => a.order - b.order);
}

你可以試試看

    data:any;
    questions : QuestionBase<any>[] = [];

    getQuestions() Observable<QuestionsBase[]> {
        return this.http.get(this.questionUrl)
            .map(res => res.json())
            .map(data => {
                this.data = data;
                this.buildQuestions(data);
    )};

    buildQuestions(data){
        for (let key in data) {
            //push Objects in this.questions array
        }
        return this.questions.sort((a, b) => a.order - b.order);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM