Search code examples
angulartypescripthttpget

Http GET, Angular


Hi I have implemented get method as the following:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CourseService {

  constructor(private httpClient: HttpClient) { }

  private courseUrl: string = 'http://localhost:8080/api/v1/courses';

  public getCourses(): Observable<Course[]> {
    return this.httpClient.get<Course[]>(this.courseUrl);
  }

}

export interface Course {
  id: number;
  title: string;
  startTime: string;
  endTime: string;
  day: string;
  totalPlaces: number;
}

Course is my pojo class

And the part of my component class:

import { Component, OnInit } from '@angular/core';
import * as Feather from 'feather-icons';
import { Course, CourseService } from '../services/course-services.service';
import { PositionEnum } from './position-enum';

@Component({
  selector: 'app-admin-dashboard',
  templateUrl: './admin-dashboard.component.html',
  styleUrls: ['./admin-dashboard.component.css']
})
export class AdminDashboardComponent implements OnInit {

  position: PositionEnum;
  course: Course[];

  constructor(private courseService: CourseService) { }

  public get positionEnum(): typeof PositionEnum {
    return PositionEnum;
  }

  ngOnInit(): void {
    this.courseService.getCourses().subscribe(value => {
      this.course = value;
    })
    Feather.replace();
  }

In html file Im trying to get any information bout whether it works, but after few tries I dont see anything. Im trying to display it by something like this: {{ course[0].id }} or this {{ course['0'].id }}. Im pretty sure that api works because Im getting response like this:

[{"id":1,"title":"Analiza matematyczna","startTime":"12:00:00","endTime":"13:30:00","day":"MONDAY","totalPlaces":10},{"id":2,"title":"Programowanie obiektowe","startTime":"15:00:00","endTime":"16:00:00","day":"MONDAY","totalPlaces":15}]

Update: I found error: Access to XMLHttpRequest at 'http://localhost:8080/api/v1/courses' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Does anyone know what the problem is? enter image description here


Solution

  • Please try add header Access-Control-Allow-Origin: *

    Also, don't forget to give Cors permission to protect the server. You can take a look at this. Cross-Origin Request Headers(CORS) with PHP headers