[Angular] Extract Implementation Details of ngrx from an Angular Application with the Facade Pattern

Extracting away the implementation details of ngrx from your components using the facade pattern creates some interesting possibilities in terms of iteratively migrating an application to ngrx. By decoupling your components from ngrx completely, this also makes testing and collaboration a lot easier. In this lesson, we will finalize our application by creating a facade to sit in between our component and ngrx and hide all of the ngrx implementation details away from our component. This has an added benefit of reducing the number of pieces that we need to export in our state module‘s barrel roll by reducing our dependency down to a single facade.

Current we have the component code like this.. we want to extract implementation detail into facade partten.

component:

import { Component, Input, OnInit, ChangeDetectionStrategy } from ‘@angular/core‘;
import { Observable } from ‘rxjs‘;

import {Role} from ‘../stores/models‘;
import { Store, select } from ‘@ngrx/store‘;
import { DashbaordState, selectAllRoles, LoadRoles } from ‘../stores‘;

@Component({
  selector: ‘dashboard‘,
  templateUrl: ‘./dashboard.component.html‘,
  styleUrls: [‘./dashboard.component.scss‘],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DashboardComponent implements OnInit {

  roles$: Observable<Role[]>;
  constructor(
    private store: Store<DashbaordState>
  ) {
    this.roles$ = this.store.pipe(
      select(selectAllRoles)
    );
  }

  ngOnInit() {
    this.store.dispatch(new LoadRoles());
  }

}

Create a facade.ts file:

import { Injectable } from "@angular/core";
import { Store, select } from ‘@ngrx/store‘;
import { DashbaordState } from ‘../reducers‘;
import { Observable } from ‘rxjs‘;
import { Role } from ‘../models‘;
import { selectAllRoles } from ‘../selectors‘;
import { LoadRoles } from ‘../actions‘;

@Injectable({
    providedIn: ‘root‘
})
export class DashboardFacade {
    roles$: Observable<Role[]>;
    constructor(
        private store: Store<DashbaordState>
    ) {
        this.roles$ = store.pipe(
            select(selectAllRoles)
          );
    }

    getRoles () {
        this.store.dispatch(new LoadRoles());
    }
}

Basiclly just move all the Store related code to the facede service.

Update the component:

import { Component, Input, OnInit, ChangeDetectionStrategy } from ‘@angular/core‘;
import { Observable } from ‘rxjs‘;

import {Role} from ‘../stores/models‘;
import { Store, select } from ‘@ngrx/store‘;
import { DashbaordState, selectAllRoles, LoadRoles } from ‘../stores‘;
import { DashboardFacade } from ‘../stores/facades/dashboard.facade‘;

@Component({
  selector: ‘dashboard‘,
  templateUrl: ‘./dashboard.component.html‘,
  styleUrls: [‘./dashboard.component.scss‘],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DashboardComponent implements OnInit {

  roles$: Observable<Role[]>;

  constructor(
    private facade: DashboardFacade
  ) {
    this.roles$ = this.facade.roles$;
  }

  ngOnInit() {
    this.facade.getRoles();
  }
}

原文地址:https://www.cnblogs.com/Answer1215/p/10340294.html

时间: 2024-08-26 15:29:23

[Angular] Extract Implementation Details of ngrx from an Angular Application with the Facade Pattern的相关文章

NgRx/Store 4 + Angular 5使用教程

这篇文章将会示范如何使用NgRx/Store 4和Angular5.@ngrx/store是基于RxJS的状态管理库,其灵感来源于Redux.在NgRx中,状态是由一个包含action和reducer的函数的映射组成的.Reducer函数经由action的分发以及当前或初始的状态而被调用,最后由reducer返回一个不可变的状态.你可以在@ngrx/store中找到我们将在下面的例子中讨论到的相关的API. Action: Action是状态的改变.它描述了某个事件的发生,但是没有指定应用的状态

angular的跨域(angular百度下拉提示模拟)和angular选项卡

1.angular中$http的服务: $http.get(url,{params:{参数}}).success().error(); $http.post(url,{params:{参数}}).success().error(); $http.jsonp(url,{params:{wd:'',cb:'JSON_CALLBACK'}}).success().error(); 注意jsonp中cb在angular中规定只能使用JSON_CALLBAC $watch(谁,做什么,false): 谁指

【Angular JS】正确调用JQuery与Angular JS脚本 - 修复Warning: Tired to load angular more than once

自己正在做一个小网站,使用Angular JS + Express JS + Mongo DB,在开发过程中,遇到一些问题,所以整理出来.希望对大家都有帮助. 这是今天解决的一个问题,Angular JS抛出Warning: Tired to load angular more than once. 前端使用的就是Angular JS,同时前端脚本中我也使用了JQuery.以下是二者Script的最初调用顺序, 在public文件夹下的index.html中: 1 <body ng-view>

[Angular Directive] Create a Template Storage Service in Angular 2

You need to define a <template> to be able to use it elsewhere in your app as a TemplateRef. You can store these TemplateRefs in a Service and then access them from any @Directive or @Component in your app. We want to create a service and a componen

野兽的Angular Api 学习、翻译及理解 - - ngRoute Angular自带的路由

野兽的ng api学习 -- ngRoute ngRoute $routeProvider 配置路由的时候使用. 方法: when(path,route); 在$route服务里添加一个新的路由. path:该路由的路径. route:路由映射信息. controller:字符串或函数,指定控制器. controllerAs:一个用于控制器的标识符名称.. template:字符串或函数,html模板. templateUrl:字符串或函数,html模板的地址. resolve:对象,一个可选的

[Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests

In a proper unit test we want to isolate external dependencies as much as possible to guarantee a reliable test outcome. Http calls represent such external dependencies. Therefore, when testing our Angular components or services that rely on data ret

CHAPTER 1 Introduction to database (第一章 数据库简介)

Chaper  Objectives  (章节目标) In this chapter you will learn:   (在这一章节中,你将学习) 1. Some common uses of database systems.   (数据库系统的一些普通扩法) 2.The characteristics of file-based systems. (基于文件系统的一些特点.) 3. The problems with the file-based systems.  (基于文件系统拥有的一

[Angular] NgRx/effect, why to use it?

See the current implementaion of code, we have a smart component, and inside the smart component we are using both 'serivce' and 'store'. In the large application, what we really want is one service to handle the application state instead of two or m

[Angular 2] ngrx/store

@ngrx/store builds on the concepts made popular by Redux and supercharges it with the backing of RxJS. The result is a tool and philosophy that will transform the way you approach state management in your Angular 2 applications. This lesson takes an