The data retrieved from the API follows this format:
{
“array1”:[
{"id”:1, ”someProperty”:”A"},
{"id":2, "someProperty”:”B”}
],
“array2”:[
{"id”:1, ”anotherProperty”:”foo”, ”lastProperty”:”foo2”},
{"id":2, "anotherProperty”:”bar”, ”lastProperty”:”bar2”}
]
}
The Dependencies class structure:
import { FirstArray } from './first-array';
import { SecondArray } from './second-array';
export class Dependencies {
constructor(
public array1: Array<FirstArray>,
public array2: Array<SecondArray>
) { }
}
The FirstArray class content:
export class FirstArray {
constructor(
public id: number,
public someProperty: string
) { }
}
The SecondArray class details:
export class SecondArray {
constructor(
public id: number,
public anotherProperty: string,
public lastProperty: string
) { }
}
Code snippet from Dependencies service.ts file:
/** GET all Dependencies from the server */
getAllDependencies (): Observable<Dependencies[]> {
return this.http.get<Dependencies[]>(apiUrl).pipe(
tap(allDependencies => this.log('fetched allDependencies')),
catchError(this.handleError('getAllDependencies', []))
);
}
Component.ts file segment:
ngOnInit() {
this.getAllDependencies();
console.log("allDependencies:",this.allDependencies);
}
allDependencies: Dependencies[];
getAllDependencies(): void {
this.DependenciesService.getAllDependencies()
.subscribe(allDependencies => this.allDependencies = allDependencies);
}
In the component file, when I use console.log(this.allDependencies), it shows up as undefined. The API data is fetched correctly and logged, yet I have trouble accessing it in my component. By stringify the object in the service file, I can see it properly:
/** GET all Dependencies from the server */
getAllDependencies (): Observable<Dependencies[]> {
return this.http.get<Dependencies[]>(apiUrl).pipe(
tap(allDependencies => this.log(JSON.stringify(allDependencies))),
catchError(this.handleError('getAllDependencies', []))
);
}
Question to resolve: What am I missing in my code structure that's causing difficulty in accessing the fetched data in the component file? It seems like there might be an issue with my TypeScript setup or a mistake in handling the data structures.