douyiavxxh02727
2016-03-08 13:17
浏览 63
已采纳

无法使用Dart和angular2客户端运行GolLang后端

I use this tutorial to make a web application with GoLang, Angular2 and Dart, but when i start backend by console command 'backend', and route in browser to "localhost:8080/" it must call method from Dart's class "Hello" but it doesn't call, and i get 404 error. All code i got from tutorial and didn't change anything. And i can't find any other tutorials. Can you explain me what wrong am i doing?

GoLang code:

func main() {
   http.Handle("/", http.FileServer(http.Dir("./app/web/")))

   fmt.Println("Text")
   http.HandleFunc("/api/hello", helloWorld)
   http.ListenAndServe(":8080", nil)

}
func helloWorld(w http.ResponseWriter, r *http.Request) {
   data := struct {
       Message string
   }{
       "Hello, World",
   }

   if err := json.NewEncoder(w).Encode(data); err != nil {
       log.Println(err)
   }
}

and angular dart code:

class AppComponent {
   Hello hello = new Hello();
}

class Hello{
  String message;

  Hello(){

    HttpRequest.getString('/api/hello')
        .then((String content) {
          Map parsedMap = JSON.decode(content);
          message = parsedMap["Message"];
        })
        .catchError((Error error) {
          print(error.toString());
        });
  }
}

and project structure :enter image description here

图片转代码服务由CSDN问答提供 功能建议

我使用此教程使用GoLang,Angular2和Dart制作Web应用程序,但是当我通过控制台命令“ backend”启动后端并在浏览器中路由到“ localhost:8080 /”时,它必须从 Dart的类“ Hello”,但没有调用,并且出现404错误。 我从教程中获得的所有代码均未更改。 而且我找不到其他教程。 您能解释一下我在做什么错吗?

GoLang代码:

  func main(){
 http.Handle(“  /“,http.FileServer(http.Dir(” ./ app / web /“)))
 
 fmt.Println(” Text“)
 http.HandleFunc(” / api / hello“,helloWorld)\  n http.ListenAndServe(“:8080”,nil)
 
} 
func helloWorld(w http.ResponseWriter,r * http.Request){
 data:= struct {
消息字符串
} {
  “ Hello,World”,
} 
 
如果err:= json.NewEncoder(w).Encode(data);  err!= nil {
 log.Println(err)
} 
} 
   
 
 

和角度飞镖代码: < pre> class AppComponent { Hello hello = new Hello(); } class Hello { 字符串消息; Hello(){ HttpRequest.getString('/ api / hello') .then((String content){ Map parsedMap = JSON.decode(content); message = parsedMap [“ Message”]; }) .catchError((错误错误 ){ print(error.toString()); }); } }

和项目结构: ”输入图像描述

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dp198879 2016-03-08 13:31
    已采纳

    The tutorial is quite old. You need to switch to HashLocationStrategy (which was the default back then as far as I know).

    See https://angular.io/docs/ts/latest/api/router/HashLocationStrategy-class.html

    Change

    bootstrap(AppComponent);
    

    to

    bootstrap(AppComponent, [
      ROUTER_PROVIDERS,
      provide(LocationStrategy, {useClass: HashLocationStrategy})
    ]);
    

    You also need to add some additional imports

    import 'package:angular2/router.dart'
        show
            HashLocationStrategy,
            LocationStrategy,
            ROUTER_PROVIDERS;
    
    点赞 评论

相关推荐 更多相似问题