简体   繁体   中英

Callback to map function in Angular2 service

In my service.ts file I have a function ( getQuestions ) that calls a HTTP service that returns a JSON. With this returned JSON ( data ) I want to call another function ( buildQuestions ) so that the result of buildQuestions is returned in getQuestions . How do I have to call the functions to return the result of buildQuestions or guarantee, that the result of buildQuestions is defined when returning it in getQuestions .

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

You can try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM