gpt4 book ai didi

go - Angular 客户端不调用后端服务

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:44 26 4
gpt4 key购买 nike

我正在开发示例应用程序,我在其中使用 Angular 5 作为前端,使用 Go Lang 作为其余服务(Web 服务)。在这里我的角度没有调用服务,但是当我通过粘贴 url 从谷歌运行并且我在 Go 中添加了 CORS 时,这些服务工作正常。这是我的角度代码:

export class TestServiceService {

private url2 ='http://localhost:8000/api/books/';

constructor(private http : HttpClient) { }

getValues()
{
debugger;
return this.http.get(this.url2);
};

}

这是我的 Go 代码 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))
}

这是服务正常运行的截图证明:

enter image description here

这里的service方法没有用angular调用,没有报错

最佳答案

您应该导入并注入(inject) 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);
};


}

关于go - Angular 客户端不调用后端服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51822516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com