Angular 、 React、 Vue 的细微差异之一: HttpClient的应用

9 篇文章 0 订阅
6 篇文章 0 订阅

背景

人们常把 Angular 、 React、 Vue 放在一起来比较, 从大的层面来说, 感觉差异很大,而在单纯的技术层面,三者之间的差异又十分有限。 这里,我们只是谈技术层面的差异,不吹哪个更牛逼:)

Angualr是一个大而全的框架,体现在什么地方呢?

人们常说起, Vue 是轻量级的框架。 这怎么理解呢? 是轻量,因为它只做了一部分功能, 毕竟作为独立开发者,一个人忙不过来啊。 这样一来,帮忙的人多了起来,到处是热心人,社区的各种插件琳琅满目,任君选用。

而 Angular 就不然了, 它把该做的都做了。 这就是为什么感觉Angular 很复杂的原因。

网络请求是最基本的模块, Angular 内置了 HttpClient, 而 React、 Vue 用到了第三方库(或者说插件)Axios 。这里,我们只谈 HTTPClient module。

首先,需要在 app.module.ts 组件中,配置 HttpClient module。 代码如下:

// app.module.ts

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

 imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpClientModule,
],
Angular 与 TypeScript的结合,可谓相得益彰,相互支持,相互支持,堪称完美!

尽管 React 和 Vue 都是宣称支持 TypeScript,但它们之间不像 Angular与TypeScript 那样战略层面的深度合作。

熟悉下 TypeScript 编程语法:

创建 User.ts , ts 是 TypeScript的缩写。如同 js是JavaScript的缩写一样。

User.ts 是一个接口(interface)文件, 定义接口(interface)的目的是: 告知 Angular 应用程序,后台传给前端的数据结构是个什么样子。

注意: 接口的定义规则。 interface 是关键字, 接口的命名规则, 首字母要大写,所以是 User 而不是 user。

在 users folder 下,创建 User.ts 文件

// User.ts

export interface User {
    id: Number;
    name: String;
    movies: Number;
  }

单有个接口文件的定义还不够,还得创建它的service (服务)。接口定义了一个数据规则,归根结底,数据还得通过网络请求从后台服务器获取。

在 users folder 中, 创建 user.service.ts 文件,

Also, inside users folder, create one file called user.service.ts. We are writing the network request code inside this file. Then we import this file inside user.component.ts file and then call service file’s function.

// user.service.ts

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

@Injectable()
export class UserService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getUsers() {
    return this
            .http
            .get(`${this.url}/results`);
        }
}

在 users.component.ts 文件中,把之前创建的 interface 和 service 引入进来

// users.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './User';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  users: User[];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService
      .getUsers()
      .subscribe((data: User[]) => {
          this.users = data;
        });
  }

}

最后,通过 users.component.html 显示后台的JSON 数据。

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Movies</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.movies }}</td>
    </tr>
  </tbody>
</table>

什么是 JSON Server ?

对于前端来说,迫切需要模拟数据,如果在后台通过 数据库的方式来提供数据,需要花费更多的时间。 还有一种更为简单的方式, 通过 JSON Server 来实现。

npm install -g json-server

还有一种安装方式 ( yarn 不常用)

yarn global add json-server

创建 一个 db.json 文件,如下:

{
    "results": [
    {
        "id": "1",
        "name": "RDJ",
        "movies": "100"
    },
    {
        "id": "2",
        "name": "Tom Holland",
        "movies": "3"
    },
    {
        "id": "3",
        "name": "Benedict Cumberbatch",
        "movies": "10"
    },
    {
        "id": "4",
        "name": "Chris Hemsworth",
        "movies": "30"
    },
    {
        "id": "5",
        "name": "Chris Evans",
        "movies": "20"
    }]
}

毕竟,JSON Server 也是一种 server, 怎么启动这个Server 呢?

启动 JSON Server 的方法:

json-server –watch src/data/db.json –port 4000

请求db.json 数据的方式,如下:
http://localhost:4000/results

最后,修改 app.module.ts 文件

// app.module.ts 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  { path: 'users', component: UsersComponent },
  { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
小结

以上是采用倒叙的方式,先创建子模块,再修改 app.module.ts 入口文件。 事实上,在企业项目开发中,都会采用这种方法, 可谓: 剥茧抽丝。

致谢

https://appdividend.com/2018/05/05/angular-6-tutorial-with-example-using-angular-cli/

参考书

学习WEB全栈,你必须阅读的2本经典书
https://blog.csdn.net/homer168/article/details/79664953

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值