I'm encountering an issue with a for loop in my component. It's giving me an error stating that the data isn't iterable, even though it's supposed to be an array. How can I resolve this problem?
this.httpService.getUser().subscribe((data: Task[]) => this.task = data);
However, when I try to implement the above code snippet, I get the following error message:
error: object access via string literals is disallowed
In my setup, I have an interface defined as follows:
Task.ts
export interface Task {
taskCategory: string;
taskTitle: string;
taskDescription: string;
taskCompleted: boolean;
}
Additionally, there is a task.json file structured like so:
{
"todoList": [
{
"taskCategory": "frontend",
"taskTitle": "fix a bug",
"taskDescription": "we have a bug with drag and drop in todo table, fix it",
"taskCompleted": false
},
{
"taskCategory": "back-end",
"taskTitle": "send data",
"taskDescription": "send data from back-end",
"taskCompleted": false
}
]
}
The corresponding http.service.ts file looks like this:
@Injectable({
providedIn: 'root'
}
)
export class HttpService {
#url = '/assets/task.json';
constructor(private http: HttpClient) { }
getUser(): Observable<Task[]> {
return this.http.get<Task[]>(this.#url);
}
}
Lastly, there's a component with the following setup:
export class AppComponent implements OnInit {
title = 'http';
task: Task[] = [];
constructor(private httpService: HttpService) { }
user: User[] = [];
ngOnInit() {
this.httpService.getUser().subscribe((data: Task[]) => {
for (let item of data) {
this.task = [{
taskCategory: item.taskCategory,
taskCompleted: item.taskCompleted,
taskDescription: item.taskDescription,
taskTitle: item.taskTitle
}]
}
});
}
}
To display the data on the HTML page, I use the following code snippet:
<div *ngFor="let item of task; index as i">
{{item.taskCategory}}
</div>