【问题标题】:Console throws "ERROR TypeError: this.cipherTextService.storeCipher is not a function"控制台抛出“错误类型错误:this.cipherTextService.storeCipher 不是函数”
【发布时间】:2020-01-03 19:11:42
【问题描述】:

一些背景

我正在开发一个密码解码应用程序。我目前处于项目的初期,对 Angular 还比较陌生。我只是想检查我是否可以创建一个service 并将其注入component,以及调用我的storeCipher(cipher) 方法。

问题

当我的logCipherText(cipher) 方法被调用时,下面的错误信息会在我的控制台中输出。 我正在运行最新版本的 Chrome

错误信息

ERROR TypeError: this.cipherTextService.storeCipher is not a function

我并没有真正尝试过太多不同的东西,因为我很确定我的代码非常接近 Angular 自己的示例。但是,我确实记录了注入的服务实例的类型,这给了我: service type: [object Object] 所以肯定不是未定义的。

我也在我的服务中对我的密码字符串做了同样的事情,它记录了: Service cipher variable type: undefined

cipher-text.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CipherTextService {
  cipher = '';

  // WHERE THE PROBLEM IS!!!
  storeCipher(cipher) {
    this.cipher = cipher;
  }

  getCipher() {
    return this.cipher;
  }

  clearCipher() {
    this.cipher = '';
  }
}

cipher-input.component.ts 注入CipherTextService

import { Component, OnInit } from '@angular/core';
import { CipherTextService } from "../cipher-text.service";

@Component({
  selector: 'app-cipher-input',
  templateUrl: './cipher-input.component.html',
  styleUrls: ['./cipher-input.component.css']
})
export class CipherInputComponent implements OnInit {

  constructor(private cipherTextService: CipherTextService) {
  }

  ngOnInit() {
  }

  // WHERE THE PROBLEM IS!!!
  logCipherText(cipher) {
    console.log("service type: " + this.cipherTextService);
    console.log("Service cipher variable type: " + this.cipherTextService.cipher);
    this.cipherTextService.storeCipher(cipher);
    console.log("stored cipher: " + this.cipherTextService.getCipher());
  }
}

cipher-input.component.html 调用logCipherText()

<div class="cipher-box">
    <input class="cipher-input" #cipher 
           placeholder="cipher text here" 
           (keyup)="logCipherText(cipher.value)"/>
</div>

我的期望

我希望得到Stringthis.cipherTextService.cipher 类型,然后我希望我的storeCipher() 方法将输入文本框中的值存储到this.cipherTextService.cipher。然后我的最后一个日志应该打印出来 stored cipher: 'whatever is typed'

【问题讨论】:

    标签: angular service components


    【解决方案1】:

    你需要暴露这个函数。

      public storeCipher(cipher: String) {
        this.cipher = cipher;
      }
    

    【讨论】:

    • 我尝试应用该解决方案,但我仍然遇到同样的问题。
    猜你喜欢
    • 2022-08-16
    • 2017-09-12
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多