【问题标题】:How to use Laravel as the backend for an Angular SPA app?如何使用 Laravel 作为 Angular SPA 应用程序的后端?
【发布时间】:2020-07-14 21:20:18
【问题描述】:

我想用 Angular(前端)和 Laravel(后端)创建一个网站。 连接这两者的最佳方式是什么?他们如何沟通? 我在搜索时发现的是超过 2 年的解决方案,所以我想知道现在是否有首选的方法来做到这一点。

我现在在做什么: 我在 laravel 中创建了 Model、Controller 和 Migration 文件,并在 LanguagesController 中调用“::all”方法从 XAMPP 中获取所有数据:

public function index()
{

    return response()->json(Languages::all(), 200, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'],
    JSON_UNESCAPED_UNICODE);

}

之后我在 api.php 中为它创建路由:

Route::get('/languages', "LanguagesController@index");

所以现在,我可以调用 www.laravelfirsttry.com/api/languages 从 Languages 表中获取所有数据。

在 Angular 中,我做了以下事情: 创建一个向 Laravel 发送请求的语言服务

private baseUrl = 'http://www.laravelfirsttry.com/api/languages';

constructor(private http: HttpClient) { }

getLanguages() {
  return this.http.get(this.baseUrl);
}

然后在我的组件中调用该服务,并将其函数的响应提供给我的变量,然后我只处理视图:

constructor(private languageService: LanguageService) { 
this.getLanguages();
}
getLanguages(): void{
this.languageService.getLanguages()
  .subscribe((res: any) => {
    this.language_tabs = res;
    console.log(res);
  }, error => {
    console.error(error);
  });
}

但问题是,当我尝试时,api 调用需要相对较长的时间才能完成。我加载了我的网站,所有内容都已加载,但在调用完成之前主要组件不可见。我觉得这看起来不太好,而且我认为我做错了什么。

总结:我在laravel中创建了一个API,然后我在Angular中调用了这个API,它的很慢。使用 Laravel 后端制作 Angular 应用程序的最佳方法是什么?

【问题讨论】:

    标签: javascript php angular laravel api


    【解决方案1】:

    首先,您需要 HttpClientModule 到您的 AppModule 的导入数组, 像这样的。

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
        imports: [
            BrowserModule,
            HttpClientModule
        ],
        declarations: [
            AppComponent
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    然后在你的组件中导入 httpClient 并添加到构造函数中

    import { HttpClient } from '@angular/common/http';
    

    然后就可以用这样的代码调用API了。

    this.http.get<any>('http://www.laravelfirsttry.com/api/languages').subscribe(data => {
                console.log(data);
                // do any operations with your data.
            })
    

    作为先决条件,请确保您的后端 Laravel API 工作正常。

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2021-03-03
      • 2018-03-20
      • 2020-10-03
      • 2021-10-07
      • 1970-01-01
      • 2018-04-12
      • 2017-03-02
      • 2019-11-19
      相关资源
      最近更新 更多