如何使用Angular在Github上进行用户搜索

图片

本文是对以下内容的回复:


本文的目的是:

  • 表明您可以在Angular上快速编写一个简单的应用程序,尽管这不是它的主要爱好,
  • 在Angular上展示应用程序的优势。

本文的目的不是:

  • 点燃另一个霍利瓦尔。

任何有兴趣的人,我都会在猫下问。

准备工作


要使用Angular,您必须全局安装angular CLI

npm install -g @angular/cli 

创建一个新的应用程序
 ng new github-ui cd github-ui 

立即创建用户组件和错误,以及用于从github接收数据的服务

 ng generate component components/user ng generate component components/error ng generate service services/github 

并将它们连接到主应用程序模块。

我们还连接了HttpClient (用于处理http请求)和ReactiveForms (用于处理表单)模块。

app.module.ts

 import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { AppComponent } from './app.component'; import { UserComponent } from './components/user/user.component'; import { ErrorComponent } from './components/error/error.component'; import { GithubService } from './services/github.service'; @NgModule({ declarations: [AppComponent, UserComponent, ErrorComponent], imports: [BrowserModule, ReactiveFormsModule, HttpClient], providers: [GithubService], bootstrap: [AppComponent] }) export class AppModule {} 

资料模型


因为 Angular使用Typescript ,而Typescript为我们提供了输入,这是描述数据模型的好习惯。

这具有以下优点:

  • 使用应用程序时方便的自动完成功能,
  • 在编译阶段进行类型匹配,
  • 使其他开发人员了解他们正在使用什么数据。

模型/ user.model.ts
 export class User { login: string; id: number; node_id: string; avatar_url: string; gravatar_id: string; url: string; html_url: string; followers_url: string; following_url: string; gists_url: string; starred_url: string; subscriptions_url: string; organizations_url: string; repos_url: string; events_url: string; received_events_url: string; type: string; site_admin: boolean; name: string; company: string; blog: string; location: string; email: string; hireable: string; bio: string; public_repos: number; public_gists: number; followers: number; following: number; created_at: string; updated_at: string; } 


数据接收服务


通常将在Angular中处理服务器请求的工作放入服务中

在先前创建的服务中,添加一种获取用户数据的方法。

服务/ github.service.ts

 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { User } from '../models/user.model'; @Injectable() export class GithubService { //      http constructor(private http: HttpClient) {} //     getUser(name: string): Observable<User> { const url = `https://api.github.com/users/${name}`; return this.http.get<User>(url); } } 

用户搜索


Angular从盒子中内置了RxJ 。 借助它和用于表单的模块,我们可以订阅以更改控制值并获取用户数据。

app.component.html

 <div class="container" [class.ready]="!!user"> <input [formControl]="findControl" placeholder="GitHub username" /> <app-user *ngIf="user" [user]="user"></app-user> <app-error *ngIf="error"></app-error> </div> 

app.component.ts

 import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { GithubService } from './services/github.service'; import { User } from './models/user.model'; import { filter, switchMap, debounceTime, catchError } from 'rxjs/operators'; import { EMPTY } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { //     findControl = new FormControl(); //   error: boolean = false; //   user: User = null; //  githubService    constructor(private githubService: GithubService) {} //    ngOnInit() { this.findControl.valueChanges .pipe( //       filter(value => value.length > 2), //     debounceTime(1000), //    switchMap(value => this.githubService.getUser(value).pipe( //   catchError(err => { this.user = null; this.error = true; return EMPTY; }) ) ) ) //   .subscribe(user => { this.user = user; this.error = false; }); } } 

其他组件


其余的组件是“愚蠢的”,即 不包含逻辑,仅显示接收到的数据。

用户组件
 <div class="github-card user-card"> <div class="header User"></div> <a class="avatar" [href]="'https://github.com/'+user.login"> <img [src]="user.avatar_url+'&s=80'" [alt]="user.name" /> </a> <div class="content"> <h1>{{user.name}}</h1> <ul class="status"> <li> <a [href]="'https://github.com/'+user.login+'?tab=repositories'"> <strong>{{user.public_repos}}</strong>Repos </a> </li> <li> <a [href]="'https://gist.github.com/'+user.login"> <strong>{{user.public_gists}}</strong>Gists </a> </li> <li> <a [href]="'https://github.com/'+user.login+'/followers'"> <strong>{{user.followers}}</strong>Followers </a> </li> </ul> </div> </div> 

 import { Component, Input, ChangeDetectionStrategy } from '@angular/core'; import { User } from '../../models/user.model'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class UserComponent { @Input() user: User; } 


错误成分
 <div class="error"> <h2>Oops!</h2> <b> User not found. </b> <p>Please try searching again.</p> </div> 

 import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-error', templateUrl: './error.component.html', styleUrls: ['./error.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ErrorComponent {} 


使用角度的优点


  • 将数据获取与他们分离,
  • 模板与逻辑的分离,
  • 清晰易懂的可扩展结构,
  • 用于处理表单和服务器的内置模块,
  • 内置的RxJ用于异步操作,
  • 强类型;检查编译错误。

源代码


的github
现场演示

结论


如上所示,可以使用不同的库,框架或纯JS编写任何应用程序(尤其是小型应用程序)。

更重要的是要了解您使用的工具,并了解它们在给定情况下的适用性。

学习成功,编写干净代码!

Source: https://habr.com/ru/post/zh-CN419933/


All Articles