I've used ASP.NET Core API. The API works fine. When I try to get data from API, it shows the following error in the browser:
header.component.ts:
import { Component, OnInit } from '@angular/core';
import { faAppleWhole } from '@fortawesome/free-solid-svg-icons';
import { faRightToBracket } from '@fortawesome/free-solid-svg-icons';
import { Topic } from '../Models/topic.model';
import { TopicService } from '../Services/topic.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
faAppleWhole = faAppleWhole;
faRightToBracket = faRightToBracket
//Defining topics (to use in the page as an array)
topics: Topic[] = [];
constructor(private topicService:TopicService)
{
}
ngOnInit(): void {
this.GetAllTopics();
}
GetAllTopics(){
this.topicService.GetAllTopics().subscribe(
response => {
this.topics = response
console.log(this.topics);
}
);
}
}
topic.service.ts:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Topic } from '../Models/topic.model';
@Injectable({
providedIn: 'root'
})
export class TopicService {
baseURL = "https://localhost:5001/api/topics";
constructor(private http: HttpClient)
{
}
GetAllTopics(): Observable<Topic[]>{
return this.http.get<Topic[]>(this.baseURL "/getalltopics");
}
}
header.component.html:
<div >
<nav *ngFor="let topic of topics">
<a href="#">{{ topic.Name }}</a>
</nav>
</div>
I have used an array for topics
but the output is not an array. What is the problem?
CodePudding user response:
Try to replace this line this.topics = response
to this.topics = response.result
CodePudding user response:
This problem was solved by making some changes in the structure of API output.
I had used the ToListAsync()
method in the action (ASP.NET Core API) without using await
. I added await
and the output turned into array.