I am developing Sample application where I am using Angular 5 for front end and Go Lang for rest services(web services). Here my angular is not calling service, but those services are working fine when I run from google by pasting url and I have added CORS in Go. Here is my angular code:
export class TestServiceService {
private url2 ='http://localhost:8000/api/books/';
constructor(private http : HttpClient) { }
getValues()
{
debugger;
return this.http.get(this.url2);
};
}
Here is my Go code package
main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
//Book struct
type Book struct {
RollNo string `json:"rollNo"`
FirstName string `json:"firstName"`
Author string `json:"author"`
}
var books []Book
func getBooks(w http.ResponseWriter, r *http.Request) {
fmt.Println("Method hit")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(books)
}
func main() {
r := mux.NewRouter()
fmt.Println("started service")
books = append(books, Book{RollNo: "1", FirstName: "Ravi", Author: "Dan"})
r.HandleFunc("/api/books/", getBooks).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", r))
}
Here is the screenshot proof where the service is working fine:
Here the service method is not called with angular and there is no errors
you should import and inject the HttpClient,
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable()
export class TestServiceService {
private url2 ='http://localhost:8000/api/books/';
constructor(private http : HttpClient) { }
getValues()
{
debugger;
return this.http.get(this.url2);
};
}
How did you call services' method in angular component?
Refer to angular guide HttpClient section. https://angular.io/guide/http#getting-json-data
Because you didn't show the code for Angular component, I don't know a root cause of your ploblem. I presume you may subscribe a Observable
, which is return value of getValues
method. It should be like below(refer to the docs):
showConfig() {
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
}