【问题标题】:How to make my frontend and backend to communicate with each other in Angular? [closed]如何让我的前端和后端在 Angular 中相互通信? [关闭]
【发布时间】:2019-08-09 22:19:25
【问题描述】:

我是网络开发的新手,想知道如何使前端 Angular 项目与后端进行通信 Angular 项目。

  • 我想将用户输入发送到我的后端。
  • 我还希望我的后端将信息发送到我的前端进行显示。

【问题讨论】:

  • Http 客户端服务?调用服务器的端点。也许如果你对开发非常陌生,请检查 firebase。
  • 我听说过一些关于 koa 的事​​情,这是否可行?
  • angular 是一个前端框架。不知道你怎么能把它用作后端。

标签: angular frontend backend


【解决方案1】:

如果我正确理解您的问题,您希望在 Angular 应用中从后端发送和接收数据。

以角度获取数据:

  1. 创建服务。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
}
  1. 创建函数以获取服务中的数据
getConfig() {
  return this.http.get(this.configUrl);
}
  1. 组件内部的调用函数
showConfig() {
  this.configService.getConfig()
    .subscribe((data: Config) => this.config = {
        heroesUrl: data['heroesUrl'],
        textfile:  data['textfile']
    });
}

向服务器发送数据

  1. 添加标题
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};
  1. 发出 POST 请求
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}
  1. 在表单提交或单击组件内部时调用服务发布方法
this.heroesService
  .addHero(newHero)
  .subscribe(hero => this.heroes.push(hero));

更多详情,请浏览 angularHttpClient 指南。

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2018-12-17
    • 2020-02-13
    • 2021-04-01
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多