0

error is in for loop in my component. It say that data isn't iterable, but it's an array. How can I fix it; I was trying to do something like

this.httpService.getUser().subscribe((data: Task[]) => this.task = data);

but it says :

error: object access via string literals is disallowed

I have an interface

Task.ts

export interface Task {
  taskCategory: string;
  taskTitle: string;
  taskDescription: string;
  taskCompleted: boolean;
}

I have a task.json

{
  "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
    }
  ]
}

My http.service.ts is :

@Injectable({
  providedIn: 'root'
}
)
export class HttpService {
  #url = '/assets/task.json';
  constructor(private http: HttpClient) { }

  getUser(): Observable<Task[]> {


    return this.http.get<Task[]>(this.#url);
  }
}

and a component

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


}

html

<div *ngFor="let item of task; index as i">
  {{item.taskCategory}}
</div>
2
  • 1
    Try with return this.http.get<Task[]>(this.#url).pipe(pluck('todoList')); Commented Jul 1, 2020 at 12:54
  • it help's. Ty a lot; But I doing it by example on youtube. And there it works. But that was ng 6 :/ Commented Jul 1, 2020 at 12:59

1 Answer 1

1

In previous versions of Angular, you had to transform the received response to JSON by doing :

http.get(url)
    .map( res => res.json() )
    .subscribe( data => ... )

In newer versions (Angular 8+, I believe) you have to observe the response's data if you want only it :

http.get(url, { observe : "response" })
    .subscribe( data => ... )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.