Ionic Http-запрос к объекту класса или к каскадированию переменных - PullRequest
0 голосов
/ 06 октября 2018

Я пытаюсь получить массив значений из API и загрузить его в объект класса и загрузить их для выбора.

Моя проблема не в том, что я не могу отправить запрошенные данные http в объект

Пробная возможность

  1. напрямую отправляет данные на объект,

  2. сохраняет во временной области и затем нажимает

я нашел много статей и постов, касающихся .map, я не уверен, как его использовать, поэтому попытался преобразовать json в массив данных и сохранить их

ниже мой код

я пытаюсь сделатькаскадирование одного выбора для загрузки другого выбора данных.

Мой API Resopnse

{"data":{"data":[{"id":"1","name":"BCA 1"},{"id":"2","name":"BCA 2"},{"id":"3","name":"BCA 3"}],"status":"success","message":"Class Found"}}

я ожидаю

, чтобы загрузить эти данные JSON из API

{"id":"1","name":"BCA 1"},{"id":"2","name":"BCA 2"},{"id":"3","name":"BCA 3"}

до class объект

class: Class[];
temp:any=[];

class Class {
    public id: number;
    public name: string;
}

this.http.post(link, data).subscribe(
    data => {

        var obj = JSON.parse(data["_body"]); 

        this.temp.push(obj["data"]["data"]);

    }, 
    error => {
        console.log(JSON.stringify(error)); 
    });

this.temp.forEach(Data => {            
    this.class.push(Data);
});

консольный вывод

{data: Array(3), status: "success", message: "Class Found"}
data: Array(3)
0: {id: "1", name: "BCA 1"}
1: {id: "2", name: "BCA 2"}
2: {id: "3", name: "BCA 3"}
length: 3
__proto__: Array(0)
message: "Class Found"
status: "success"
__proto__: Object

1 Ответ

0 голосов
/ 06 октября 2018

Пожалуйста, дайте мне знать, если это не правильно, но, основываясь на комментариях, вы сможете получить массив data, выполнив следующее:

public classArray: Array<Class> = [];

public yourMethod(): void {

    this.http.post(link, data).subscribe(
        response => {

            // Get the body of the response
            const body = response.json();

            // Get the data array within the data property
            const data = body.data.data;

            // This should print the data in the console
            console.log(data);

            // Add the items to the array
            this.classArray.push(...data);

            // This should print the classArray array in the console
            console.log(this.classArray);
        },
        error => {
            console.log(error);
        });
}

РЕДАКТИРОВАТЬ

Вы также можете использовать оператор map, чтобы получить тело запроса, например:

import { map } from 'rxjs/operators/map';

// ...

public classArray: Array<Class> = [];

public yourMethod(): void {

    this.http.post(link, data)
        .pipe(
            map(response => response.json())
        )        
        .subscribe(
            body => {

                // Get the data array within the data property
                const data = body.data.data;

                // This should print the data in the console
                console.log(data);

                // Add the items to the array
                this.classArray.push(...data);

                // This should print the classArray array in the console
                console.log(this.classArray);
            },
            error => {
                console.log(error);
            });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...