【问题标题】:Angular: service and ngrx return undefinedAngular:服务和ngrx返回未定义
【发布时间】:2021-08-16 13:52:50
【问题描述】:

我正在学习 Angular、DI、Services 和 Ngrx,但我遇到了一个我无法理解的问题

当我记录 this.getBase() 和 this.baseRateSaving 时,我在控制台中得到了值,但是当我尝试将它注入到我的字符串插值中时,我得到了未定义。

我尝试不使用 getbase() 方法,所以使用 this。 baseRateSaving 但我的编辑器告诉我'属性'baseRateSaving' 在其初始化之前使用'

代码如下:

import { BodyCard, HeaderCard, IconDetails } from '@fortuneo/components/src/app/components/card/card.model';
import { CardsOptionsContextService } from './cards-options-context.service';
import { Injectable, OnDestroy } from '@angular/core';
import { combineLatest } from 'rxjs';
import { subscriptionSelector } from '../../../store/subscription/subscription.state';
import { savingsParametersSelector } from '../../../store/parameters/parameters.state';
import { Subscription as RXSubscription } from 'rxjs/internal/Subscription';
import { Store } from '@ngrx/store';
import { AppState } from '../../../store/store.model';
import { Product } from '@fortuneo-models/subscription';

export interface CardOptions {
  id: string;
  iconDetails: IconDetails;
  headerCard: HeaderCard;
  bodyCard: BodyCard;
  context?: {}
}

@Injectable()
export class CardsOptionsService implements OnDestroy {
  products: Product[];
  baseRateSaving: number;
  private data$: RXSubscription;

  constructor(private cardsOptionsContext: CardsOptionsContextService,
              private store: Store<AppState>) {
    this.data$ = combineLatest([
      this.store.select(subscriptionSelector),
      this.store.select(savingsParametersSelector)
    ]).subscribe(([subscription, savingsParameters]) => {
      this.products = subscription.products;
      this.baseRateSaving = savingsParameters.baseRate;
    });
    console.log(this.baseRateSaving);
    console.log(this.getBase());
  }

  getBase() {
    return this.baseRateSaving;
  }
}
...
...
      headerCard: {
        title: '<h2 class="title">Livret +</h2>',
        subTitle: `<p class='subtitle'>Taux de base : ${this.getBase()}% bruts(2)</p>`
      },

我真的迷路了

【问题讨论】:

    标签: angular service ngrx-store


    【解决方案1】:

    自从我用 Angular 编程以来已经有很长时间了,我可能是错的,但你可以尝试用 ngOnInit 而不是构造函数来做。你应该看看 Angular 的生命周期。

    ngOnInit() {
       this.logIt(`OnInit`);
    }
    

    【讨论】:

      【解决方案2】:

      由于这是一个@Injectable() 类,因此您不能直接放置 getBase()。

      将 headerCard 变量放入您创建的组件中,然后您需要在构造函数中注入 CardsOptionsService 并调用 getBase()。

      @Injectable()
      export class CardsOptionsService {
        products: Product[];
        baseRateSaving: number;
        private data$: RXSubscription;
      
        constructor(private cardsOptionsContext: CardsOptionsContextService,
                    private store: Store<AppState>) {
          this.data$ = combineLatest([
            this.store.select(subscriptionSelector),
            this.store.select(savingsParametersSelector)
          ]).subscribe(([subscription, savingsParameters]) => {
            this.products = subscription.products;
            this.baseRateSaving = savingsParameters.baseRate;
          });
          console.log(this.baseRateSaving);
          console.log(this.getBase());
        }
      
        getBase() {
          return this.baseRateSaving;
        }
      }
      

      这个服务你需要注入你的组件(不要在你的服务中使用组件生命周期钩子(OnInit, OnDestroy))。

      @Component({ selector: 'header' })
      class HeaderComponent implements OnInit () {
      
        headerCard: {
          title: '<h2 class="title">Livret +</h2>',
          subTitle: `<p class='subtitle'>Taux de base : ${this.base}% bruts(2)</p>`
        },
        constructor(private cardsOptionsService: CardsOptionsService) {}
        get base() {
          return this.cardsOptionsService.getBase();
        }
      
      }
      

      要将字符串转换为 html,您需要 DomSanitizer。 请参考下文。

      https://stackblitz.com/edit/angular-safehtml

      【讨论】:

      • 感谢您的回复,我想将标头变量留在服务中,我可以在控制台中获取 baseRateSaving 的值,但在此行中未定义:``` subTitle: &lt;p class='subtitle'&gt;Taux de base : ${this.base}% bruts(2)&lt;/p&gt; ```
      • 好的。您可以在服务中使用 get base() { return this.baseRateSaving; } 而不是在您的服务中使用 getBase() 吗?
      • 感谢这个想法,但它不起作用。我找到了一个解决方案:我将构造函数中的代码移动到一个新服务中并以这种方式调用它:subTitle:&lt;p class='subtitle'&gt;Taux de base : ${this.cardOptionsUtils.baseRateSaving.toString()}% bruts(2)&lt;/p&gt;,它可以工作。现在如果有人能告诉我为什么第一个解决方案不起作用,我会很高兴:)
      猜你喜欢
      • 2019-01-10
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多