Aya Abdelaziz
Aya Abdelaziz

Reputation: 375

loop in array in JSON using typescript

i wanna loop for subjects array in JSON response

JSON Response :

{
"$id": "1",
"Council_ID": 116,
"number": "67",
"subjects": [
    {
        "$id": "2",
        "subjectCode": "67",
        "type": 4,
    },
    {
        "$id": "3",
        "subjectCode": "67",
        "type": 4,
    }
   ]
}

model.component.ts:

this.dataStorageService.storeSubjects(newSubject, this.meetingID)
        .subscribe(
        response => {
            this.dataStorageService.getCouncilId(this.meetingID).subscribe(response => {
                this.subjectsWithID = response.json();
                this.sublength = this.subjectsWithID.subjects.length;
                console.log(this.sublength);
                for(let i = 0 ; i <= this.sublength; i++){
                    this.typee = this.subjectsWithID.subjects[i].type;
                    this.dataStorageService.getSubjectTypeId(this.typee).subscribe(response =>{
                        this.namesOfSub = Array.of( response.json());
                        console.log(this.namesOfSub)
                    });
                }
                // console.log(this.typee, 'bla bla');
            });
            this.addSubjectForm.reset();
            this.router.navigate(['/model']);
            return true;

That give me error : - Property 'subjects' does not exist on type 'any[]'. there is any suggestion to get rid of this error ?

Upvotes: 0

Views: 87

Answers (1)

Fateh Mohamed
Fateh Mohamed

Reputation: 21387

ok using httpClient , you can't get the property this.subjectsWithID.subjects, but usinh http it is possible, it's because httpClinet when it parse the result it does know the share of your object, you have to give a type for your result or you can access your property like this:

  this.subjectsWithID['subjects']

or you can specify the type using interface :

    return this.http.get<myObject>(...url)

 interface Sidebar {
    id: number;
    Council_ID: number,
    number: number,
    subjects: [...
  }

Upvotes: 1

Related Questions