发表在< / div >< / div >

角训练

伪造你的Angular后端,直到你成功

为什么是模拟API?

原型设计

嘲笑

教学

什么是JSON服务器?

设置JSON服务器

搭建一个新的Angular应用程序

Ng new my-app——defaults

更改目录为我的程序

我的程序光盘

安装JSON服务器

NPM安装——保存json-server

创建数据库文件


“团队”:(

“id”: 1、
"name": "FC Barcelona",
“教练”:“埃内斯托·巴尔韦德”,
描述:“世界上最好的足球队!”
},

“id”: 2
"name": "Real Madrid",
“教练”:“齐达内”,
"description": "世界上最差的足球队!"


创建路由映射文件


:“/ api / * / 1美元”

添加一个脚本来启动服务器

"api": "json-server api/db. "api/routes。json——no-cors = true”

启动模拟API

NPM运行API

从Angular中与模拟API通信

设置HttpClientModule

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
从@angular/common/http导入{HttpClientModule};

@NgModule ({
声明:[
AppComponent
),
进口:[
BrowserModule,
HttpClientModule,
),
引导(AppComponent):
})
导出类AppModule {}

向后端发出请求

import {Component} from @angular/core;
从@angular/common/http导入{HttpClient};

@ component ({
选择器:“app-root”,
templateUrl:“。/ app.component.html”,
styleUrls(“。/ app.component.css”):
})
导出类AppComponent {
Teams $ = this.http.get('http://localhost:3000/api/teams');

构造函数(私有http: HttpClient) {}

显示团队列表

< h2 > < / h2 >团队

< h3 > {{team.name}} < / h3 >
< p > {{team.description}} < / p >
< / div >

启动应用程序

发球——开球

解决CORS问题

使我们的HTTP调用相对

teams$: Observable = this.http.get('/api/teams');

创建代理配置对象


" / api ": {
“目标”:“http://localhost: 3000”

更新工作区配置文件以使用代理


"服务":{
“建设者”:“@angular-devkit / build-angular: dev-server”,
"选项":{
“browserTarget”:“我的程序:构建”,
:“proxyConfig proxy.conf.json”
},
"配置":{
"生产":{
“browserTarget”:“我的程序:构建:生产”



重新启动服务器

总结

火绒萨尔

Amadou is a Frontend Software Engineer from Senegal based in France . He’s a Google Developer Expert in Angular, and currently works at Air France.

Baidu
map