第一个 Angular 项目 - 添加服务

news2024/10/7 8:24:45

第一个 Angular 项目 - 添加服务

这里主要用到的内容就是 [Angular 基础] - service 服务 提到的

前置项目在 第一个 Angular 项目 - 动态页面 这里查看

想要实现的功能是简化 shopping-listrecipe 之间的跨组件交流

回顾一下项目的结构:

❯ tree src/app/
src/app/
├── directives
├── header
├── recipes
│   ├── recipe-detail
│   ├── recipe-list
│   │   ├── recipe-item
│   ├── recipe.model.ts
├── shared
│   └── ingredient.model.ts
└── shopping-list
    ├── shopping-edit

11 directories, 31 files

层级结构相对来说还是有一点点复杂的,所以如果在 app 层构建一个对应的变量和事件再一层层往下传,无疑是一件非常麻烦的事情(尤其 V 层和 VM 层都要进行事件传输的对应变化),而使用 service 就能相对而言比较简单的解决这个问题

创建新的 service

这里主要会创建两个 services:

src/app/
├── services
│   ├── ingredient.service.ts
│   └── recipe.service.ts

一个用来管理所有的 ingredients——这部分是放在 shopping-list 中进行展示的,另一个就是管理所有的 recipes

ingredient service

实现代码如下:

@Injectable({
  providedIn: 'root',
})
export class IngredientService {
  ingredientChanged = new EventEmitter<Ingredient[]>();

  private ingredientList: Ingredient[] = [
    new Ingredient('Apples', 5),
    new Ingredient('Tomatoes', 10),
  ];

  constructor() {}

  get ingredients() {
    return this.ingredientList.slice();
  }

  addIngredient(Ingredient: Ingredient) {
    this.ingredientList.push(Ingredient);
    this.ingredientChanged.emit(this.ingredients);
  }

  addIngredients(ingredients: Ingredient[]) {
    this.ingredientList.push(...ingredients);
    this.ingredientChanged.emit(this.ingredients);
  }
}

代码分析如下:

  • Injectable

    这里使用 providedIn: 'root' 是因为我想让所有的组件共享一个 service,这样可以满足当 ingredient 页面修改对应的食材,并且将其发送到 shopping-list 的时候,数据可以进行同步渲染

  • ingredientChanged

    这是一个 event emitter,主要的目的就是让其他的组件可以 subscribe 到事件的变更

    subscribe 是之前的 service 笔记中没提到的内容,这里暂时不会细舅,不过会放一下用法

  • get ingredients()

    一个语法糖,这里的 slice 会创造一个 shallow copy,防止意外对数组进行修改

    也可以用 lodash 的 cloneDeep,或者单独创建一个函数去进行深拷贝

  • add 函数

    向数组中添加元素,并向外发送数据变更的信号

recipe service

@Injectable()
export class RecipeService {
  private recipeList: Recipe[] = [
    new Recipe('Recipe 1', 'Description 1', 'http://picsum.photos/200/200', [
      new Ingredient('Bread', 5),
      new Ingredient('Ginger', 10),
    ]),
    new Recipe('Recipe 2', 'Description 2', 'http://picsum.photos/200/200', [
      new Ingredient('Chicken', 10),
      new Ingredient('Bacon', 5),
    ]),
  ];

  private currRecipe: Recipe;

  recipeSelected = new EventEmitter<Recipe>();

  get recipes() {
    return this.recipeList.slice();
  }

  get selectedRecipe() {
    return this.currRecipe;
  }
}

这里主要讲一下 Injectable,因为 recipe service 的部分应该被限制在 recipe 这个组件下,所以这里不会采用 singleton 的方式实现

其余的实现基本和上面一样

修改 recipe

这里依旧是具体业务具体分析:

  • recipe

    这里需要获取 activeRecipe + ngIf 去渲染 recipe-detail 部分的内容,如:

    没有选中 recipe选中了 recipe
    在这里插入图片描述在这里插入图片描述
  • recipe-detail

    这里需要 activeRecipe 去渲染对应的数据,如上图

  • recipe-list

    这里需要 recipes 去完成循环,渲染对应的 recipe-item

  • recipe-item

    这里需要 activeRecipe 完成对 active 这个 class 的添加

recipe 组件的修改

  • V 层修改:

    <div class="row">
      <div class="col-md-5">
        <app-recipe-list></app-recipe-list>
      </div>
      <div class="col-md-7">
        <app-recipe-detail
          [activeRecipe]="activeRecipe"
          *ngIf="activeRecipe; else noActiveRecipe"
        ></app-recipe-detail>
        <ng-template #noActiveRecipe>
          <p>Please select a recipe to view the detailed information</p>
        </ng-template>
      </div>
    </div>
    
  • VM 层修改

    @Component({
      selector: 'app-recipes',
      templateUrl: './recipes.component.html',
      providers: [RecipeService],
    })
    export class RecipesComponent implements OnInit, OnDestroy {
      activeRecipe: Recipe;
    
      constructor(private recipeService: RecipeService) {}
    
      ngOnInit() {
        this.recipeService.recipeSelected.subscribe((recipe: Recipe) => {
          this.activeRecipe = recipe;
        });
      }
    
      ngOnDestroy(): void {
        this.recipeService.recipeSelected.unsubscribe();
      }
    }
    

这里主要是对 V 层进行了一些修改,减少了一些数据绑定。大多数的用法这里都是之前在 service 的笔记中提到的,除了这个 subscribe 的使用

简单的说,在 subscribe 之后,每一次 event 触发后,在这个 subscription 里,它都可以获取 event 中传来的信息,并进行对应的更新操作

recipe-list 组件的修改

  • V 层修改如下

    <div class="row">
      <div class="col-xs-12">
        <button class="btn btn-success">New Recipe</button>
      </div>
    </div>
    <hr />
    <div class="row">
      <div class="col-xs-12">
        <app-recipe-item
          *ngFor="let recipe of recipes"
          [recipe]="recipe"
        ></app-recipe-item>
      </div>
    </div>
    
  • VM 层修改如下

    @Component({
      selector: 'app-recipe-list',
      templateUrl: './recipe-list.component.html',
      styleUrl: './recipe-list.component.css',
    })
    export class RecipeListComponent implements OnInit {
      recipes: Recipe[];
    
      constructor(private recipeService: RecipeService) {}
    
      ngOnInit() {
        this.recipes = this.recipeService.recipes;
      }
    }
    

这里主要就是获取数据的方式变了,也不需要向下传递 @Input,向上触发 @Output

reccipe-item 组件的修改

  • V 层

    <a
      href="#"
      class="list-group-item clearfix"
      (click)="onSelectedRecipe()"
      [ngClass]="{ active: isActiveRecipe }"
    >
      <div class="pull-left">
        <h4 class="list-group-item-heading">{{ recipe.name }}</h4>
        <p class="list-group-item-text">{{ recipe.description }}</p>
      </div>
      <span class="pull-right">
        <img
          [src]="recipe.imagePath"
          [alt]="recipe.name"
          class="image-responsive"
          style="max-height: 50px"
        />
      </span>
    </a>
    

    这里做的另外一个修改就是把 a 标签移到了 list-item 去处理,这样语义化相对更好一些

  • VM 层

    @Component({
      selector: 'app-recipe-item',
      templateUrl: './recipe-item.component.html',
      styleUrl: './recipe-item.component.css',
    })
    export class RecipeItemComponent implements OnInit, OnDestroy {
      @Input() recipe: Recipe;
      isActiveRecipe = false;
    
      constructor(private recipeService: RecipeService) {}
    
      ngOnInit() {
        this.recipeService.recipeSelected.subscribe((recipe: Recipe) => {
          this.isActiveRecipe = recipe.isEqual(this.recipe);
        });
      }
    
      onSelectedRecipe() {
        this.recipeService.recipeSelected.emit(this.recipe);
      }
    
      ngOnDestroy(): void {
        this.recipeService.recipeSelected.unsubscribe();
      }
    }
    

    这里变化稍微有一点多,主要也是针对 activeRecipeonSelectedRecipe 的修改。

    前者的判断我在 model 写了一个 isEqual 的方法用来判断名字、数量、图片等是否一样,当然只用这个方法的话还是有可能会出现数据碰撞的,因此写案例的时候我尽量不会用同一个名字去命名 ingredient。基于这个前提下,那么就可以判断当前的 recipe 是不是被选中的 recipe,同时添加 active 这一类名做更好的提示

    使用 subscribe 也是基于同样的理由,需要捕获 recipe 的变动

    onSelectedRecipe 的变化倒是没有太多,同样会触发一个事件,不过这个事件现在保存在 recipeService 中

    目前的实现是整个 recipe 都共享一个 service,因此这里 emit 的事件,在整个 recipe 组件下,只要 subscribe 了,就只会是同一个事件

recipe-detail 组件的修改

  • V 层

    <div class="row">
      <div class="col-xs-12">
        <img
          src="{{ activeRecipe.imagePath }}"
          alt=" {{ activeRecipe.name }} "
          class="img-responsive"
        />
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12">
        <h1>{{ activeRecipe.name }}</h1>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12">
        <div class="btn-group" appDropdown>
          <button type="button" class="btn btn-primary dropdown-toggle">
            Manage Recipe <span class="caret"></span>
          </button>
          <ul class="dropdown-menu">
            <li>
              <a href="#" (click)="onAddToShoppingList()">To Shopping List</a>
            </li>
            <li><a href="#">Edit Recipe</a></li>
            <li><a href="#">Delete Recipe</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12">{{ activeRecipe.description }}</div>
    </div>
    <div class="row">
      <div class="col-xs-12">
        <ul class="list-group">
          <li
            class="list-group-item"
            *ngFor="let ingredient of activeRecipe.ingredients"
          >
            {{ ingredient.name }} - {{ ingredient.amount }}
          </li>
        </ul>
      </div>
    </div>
    
  • VM 层

    @Component({
      selector: 'app-recipe-detail',
      templateUrl: './recipe-detail.component.html',
      styleUrl: './recipe-detail.component.css',
    })
    export class RecipeDetailComponent {
      @Input() activeRecipe: Recipe;
    
      constructor(private ingredientService: IngredientService) {}
    
      onAddToShoppingList() {
        this.ingredientService.addIngredients(this.activeRecipe.ingredients);
      }
    }
    

这里通过调用 ingredient service 将当前 recipe 中的 ingredient 送到 shopping-list 的 view 下,效果如下:

在这里插入图片描述

这里没有做 unique key 的检查,而且实现是通过 Array.push 去做的,因此只会无限增加,而不是更新已有的元素。不过大致可以看到这个跨组件的交流是怎么实现的

修改 shopping-list

这里的实现和 recipe 差不多,就只贴代码了

shopping-list 组件的修改

  • V 层

    <div class="row">
      <div class="col-xs-10">
        <app-shopping-edit></app-shopping-edit>
        <hr />
        <ul class="list-group">
          <a
            class="list-group-item"
            style="cursor: pointer"
            *ngFor="let ingredient of ingredients"
          >
            {{ ingredient.name }} ({{ ingredient.amount }})
          </a>
        </ul>
      </div>
    </div>
    
  • VM 层

    @Component({
      selector: 'app-shopping-list',
      templateUrl: './shopping-list.component.html',
      styleUrl: './shopping-list.component.css',
    })
    export class ShoppingListComponent implements OnInit, OnDestroy {
      ingredients: Ingredient[] = [];
    
      constructor(private ingredientService: IngredientService) {}
    
      ngOnInit(): void {
        this.ingredients = this.ingredientService.ingredients;
        this.ingredientService.ingredientChanged.subscribe(
          (ingredients: Ingredient[]) => {
            this.ingredients = ingredients;
          }
        );
      }
    
      ngOnDestroy(): void {
        this.ingredientService.ingredientChanged.unsubscribe();
      }
    }
    

同样也是一个 subscription 的实现去动态监听 ingredients 的变化

shopping-edit 组件的修改

  • V 层

    <div class="row">
      <div class="col-xs-12">
        <form>
          <div class="row">
            <div class="col-sm-5 form-group">
              <label for="name">Name</label>
              <input type="text" id="name" class="form-control" #nameInput />
            </div>
            <div class="col-sm-2 form-group">
              <label for="amount">Amount</label>
              <input
                type="number"
                id="amount"
                class="form-control"
                #amountInput
              />
            </div>
          </div>
          <div class="row">
            <div class="col-xs-12">
              <div class="btn-toolbar">
                <button
                  class="btn btn-success mr-2"
                  type="submit"
                  (click)="onAddIngredient(nameInput)"
                >
                  Add
                </button>
                <button class="btn btn-danger mr-2" type="button">Delete</button>
                <button class="btn btn-primary" type="button">Edit</button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
    

    这里添加了一个按钮的功能,实现添加 ingredient

  • VM 层

    @Component({
      selector: 'app-shopping-edit',
      templateUrl: './shopping-edit.component.html',
      styleUrl: './shopping-edit.component.css',
    })
    export class ShoppingEditComponent {
      @ViewChild('amountInput', { static: true })
      amountInput: ElementRef;
    
      constructor(private ingredientService: IngredientService) {}
    
      onAddIngredient(nameInput: HTMLInputElement) {
        this.ingredientService.addIngredient(
          new Ingredient(nameInput.value, this.amountInput.nativeElement.value)
        );
      }
    }
    

    这里的 onAddIngredient 实现方式和添加整个 list 基本一致,也就不多赘述了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1467168.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

第3部分 原理篇2去中心化数字身份标识符(DID)(3)

3.2.2.4. DID文档 (DID Document) 本聪老师&#xff1a;DID标识符和DID URL还都只是ID&#xff0c;必须为它附加一个基本属性才可以证明是该主体独有的。这个就是我们下面介绍的DID文档。 本聪老师&#xff1a;每个DID标识符都唯一对应一个DID文档&#xff0c;也可以说&#x…

什么是负载均衡集群?

目录 1、集群是什么&#xff1f; 2、负载均衡集群技术 3、负载均衡集群技术的实现 4、实现效果如图 5、负载均衡分类 6、四层负载均衡&#xff08;基于IP端口的负载均衡&#xff09; 7、七层的负载均衡&#xff08;基于虚拟的URL或主机IP的负载均衡) 8、四层负载与七层…

Typora+PicGo+super-prefix+阿里云OSS设置图床

&#x1f308;个人主页&#xff1a;godspeed_lucip &#x1f525; 系列专栏&#xff1a;实用工具 1 TyporaPicGosuper-prefix阿里云OSS设置图床1.1 设置阿里云OSS1.2 以时间戳命名图片1.2.1 安装super-prefix1.2.2 设置配置文件 1.3 批量上传图片遇到的问题1.4 参考资料 2 将ma…

OpenHarmony JS和TS三方组件使用指导

OpenHarmony JS和TS三方组件介绍 OpenHarmony JS和TS三方组件使用的是OpenHarmony静态共享包&#xff0c;即HAR(Harmony Archive)&#xff0c;可以包含js/ts代码、c库、资源和配置文件。通过HAR&#xff0c;可以实现多个模块或者多个工程共享ArkUI组件、资源等相关代码。HAR不…

robots.txt 文件规则

robots.txt 是一种用于网站根目录的文本文件&#xff0c;其主要目的在于指示网络爬虫&#xff08;web crawlers&#xff09;和其他网页机器人&#xff08;bots&#xff09;哪些页面可以抓取&#xff0c;以及哪些页面不应该被抓取。可以看作是网站和搜索引擎机器人之间的一个协议…

Element table 实现表格行、列拖拽功能

安装包 npm install sortablejs --save <template><div class"draggable" style"padding: 20px"><el-table row-key"id" :data"tableData" style"width: 100%" border><el-table-columnv-for"(it…

osg qt5.15 osg3.6.3 osgEarth3.1 编译爬山

Demo演示&#xff1a;Qt5.15.2OSG3.6.3OsgEarth3.1的QtCreator下的msvc2019x64版本 osgQt编译 步骤一&#xff1a;下载解压 步骤二&#xff1a;CMake配置 步骤三&#xff1a;CMake配置添加osg环境 步骤四&#xff1a;CMake配置添加Qt环境 步骤五&#xff1a;CMake修改CMakeLis…

【数据结构】C语言实现图的相关操作

图 图&#xff08;Graph&#xff09;是由顶点的有穷非空集合和顶点之间边的集合组成&#xff0c;通常表示为&#xff1a;G(V,E)&#xff0c;其中&#xff0c;G 表示一个图&#xff0c;V 是图 G 中顶点的集合&#xff0c;E 是图 G 中边的集合。 术语 无向图&#xff1a;每条边…

使用HiveMQ实现Android MQTT

MQTT官网&#xff1a;https://mqtt.org/ 百度Android MQTT&#xff0c;或者B站上搜索&#xff0c;发现大多使用https://github.com/eclipse/paho.mqtt.android&#xff0c;这是Eclipse的一个Android MQTT客户端实现库&#xff0c;但是我发现这个库在运行到高版本的手机上时报错…

Unet 高阶分割网络实战、多类别分割、迁移学习(deeplab、resnet101等等)

1、前言 Unet 图像分割之前介绍了不少&#xff0c;具体可以参考 图像分割专栏 为了实现多类别的自适应分割&#xff0c;前段时间利用numpy的unique函数实现了一个项目。通过numpy函数将mask的灰度值提取出来&#xff0c;保存在txt文本里&#xff0c;这样txt里面就会有类似0 1…

基于微信小程序的垃圾分类系统,附源码

博主介绍&#xff1a;✌程序员徐师兄、7年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;…

Java SpringBoot测试OceanBase

对上篇mysql导入到OceanBase中的数据库进行代码测试&#xff0c;写了个demo包含测试方法&#xff0c;在原mysql库中成功执行&#xff0c;迁移到OceanBase时看是否能不修改业务代码而成功执行测试方法&#xff1a; 代码基于SpringBoot MyBastis测试增删改查、批量新增、多表联…

在项目中应用设计模式的实践指南

目录 ✨✨ 祝屏幕前的您天天开心&#xff0c;每天都有好运相伴。我们一起加油&#xff01;✨✨ &#x1f388;&#x1f388;作者主页&#xff1a; 喔的嘛呀&#x1f388;&#x1f388; 引言 一. 单例模式&#xff08;Singleton Pattern&#xff09; 1、实现单例模式的方式 1…

List集合之UML、特点、遍历方式、迭代器原理、泛型、装拆箱及ArrayList、LinkedList和Vector的区别

目录 ​编辑 一、什么是UML 二、集合框架 三、List集合 1.特点 2.遍历方式 3.删除 4.优化 四、迭代器原理 五、泛型 六、装拆箱 七、ArrayList、LinkedList和Vector的区别 ArrayList和Vector的区别 LinkedList和Vector的区别 一、什么是UML UML&#xff08;Unif…

20个改善编码的Python异常处理技巧,让你的代码更高效

异常处理是写好代码的一个重要的方面&#xff0c;虽然许多开发人员都熟悉基本的try-except块&#xff0c;但是有很多更深入的知识可以使异常处理更高效、更可读和更python化。所以本文将介绍关于Python异常的20个可以显著改善编码的Python异常处理技巧&#xff0c;这些技巧可以…

C/C++内存管理学习【new】

文章目录 一、C/C内存分布二、C语言中动态内存管理方式&#xff1a;malloc/calloc/realloc/free三、C内存管理方式3.1 new/delete操作内置类型3.2 new和delete操作自定义类型四、operator new与operator delete函数五、new和delete的实现原理5.1 内置类型 六、定位new表达式(pl…

天锐绿盾 | 文件数据\资料防泄漏软件 \ 自动智能透明加密保护

怎么防止公司办公终端文件数据资料外泄? 防止公司办公终端文件数据资料外泄是非常重要的&#xff0c;以下是一些有效的措施&#xff1a; 限制访问权限&#xff1a;根据员工的职责和需求&#xff0c;设定文件和数据资料的访问权限。确保只有授权人员才能访问敏感信息。 加密存…

2024图像处理分析与信息工程国际学术会议(IACIPIE2024)

2024图像处理分析与信息工程国际学术会议(IACIPIE2024) 会议简介 2024图像处理分析与信息工程国际学术会议&#xff08;IACIPIE2024&#xff09;将在中国长沙举行。 IACIPIE2024是一个年度会议&#xff0c;探讨图像处理分析和信息工程相关领域的发展和影响&#xff0c;旨在介…

数字孪生低代码平台盘点(一):厂家介绍

特别说明&#xff1a;本文根据网上资料搜集整理而成&#xff0c;排名不分先后&#xff0c;配图是为了更好地阅读体验&#xff0c;并非表明该图为该平台所生产。如有错误之处&#xff0c;请在评论区提出。 一、优锘ChartBuilder 优锘ChartBuilder是一款基于Web的数据可视化工具…

C++的vector容器->基本概念、构造函数、赋值操作、容量和大小、插入和删除、数据存取、互换容器、预留空间

#include<iostream> using namespace std; #include <vector> //vector容器构造 void printVector(vector<int>& v) { for (vector<int>::iterator it v.begin(); it ! v.end(); it) { cout << *it << " "…