控制台引发“错误TypeError:this.cipherTextService.storeCipher不是函数”

时间:2019-08-30 14:07:04

标签: angular service components

某些背景

我正在开发密码解码应用程序。我目前在项目刚开始时,对 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>

我期望的结果

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

1 个答案:

答案 0 :(得分:0)

您需要公开该功能。

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