Bind a service property to a component property with proper change tracking

前端 未结 3 853
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 12:19

Consider the utterly simple Angular 2 service:

import { Injectable } from \'@angular/core\';
import {Category} from \"../models/Category.model\";

@Injectabl         


        
3条回答
  •  粉色の甜心
    2021-01-01 12:59

    Not too big of a boilerplate chunk. But what's going on here is that when the service is created or you make a call however your want to handle it. Your component will know about it through the subscription and then update your local variable to the new value. Allowing you to access it as this.activeCategory.

    import { Injectable } from '@angular/core';
    import {Category} from "../models/Category.model";
    import {Subscription}   from 'rxjs/Subscription';
    
    @Injectable()
    export class CategoryService {
        private _categoryObject = new Subject();
        categoryObjectAnnounced$ = this._categoryObject;
        private _activeCategoryObject = new Subject();
        activeCategoryObjectAnnounced$ = this._activeCategoryObject;
        activeCategory: Category|{} = {};
        constructor() {};
    }
    
    
    import { Component, OnInit } from '@angular/core';
    import {CategoryService} from "../shared/services/category.service";
    import {Category} from "../shared/models/Category.model";
    import {Subscription} from 'rxjs/Subscription';
    @Component({
        selector: 'my-selector',
        template: `
        {{activeCategory.Name}}
    {{category.Name}}
    `, }) export class MySelectorComponent implements OnInit { category:Category|{} = {}; activeCategory:ActiveCategory|{} = {}; activeCategorySubscription : Subscription; categorySubscription : Subscription; constructor(public categoryService:CategoryService){ this.categorySubscription= this.categoryService.categoryObjectAnnounced$.subscribe((category) => { this.category= category; }); this.activeCategorySubscription= this.categoryService.activeCategoryObjectAnnounced$.subscribe((active) => { this.activeCategory= active; }); }; ngOnInit() { }; }

提交回复
热议问题