【问题标题】:why the service does not return an encoded string?为什么服务不返回编码字符串?
【发布时间】:2017-12-26 18:22:02
【问题描述】:

我提供编码密码的服务。此服务使用ts-md5:

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

import { Md5 } from 'ts-md5/dist/md5';


@Injectable()
export class HashService {

  constructor() { }

  generate(str): Observable<string>{
    const h = Md5.hashStr(str);
    console.log(h, typeof h);
    return h;
  }

}

从我订阅服务的组件:

this.hashService.generate(this.form.value.password).subscribe((hash) => {
  console.log(hash);
});

但控制台显示以下错误消息:

src/app/shared/services/hash.service.ts(15,5) 中的错误:错误 TS2322: 键入'字符串 | Int32Array' 不可分配给类型 'Observable'。 类型 'string' 不可分配给类型 'Observable'

我试图指定一个更常见的类型:

generate(str): Observable<any>{

但问题依然存在

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    Md5.hashStr() 不返回 Observable,它返回一个字符串。您不需要返回可观察对象并订阅。您可以简单地返回字符串

    // service.ts
    generate(str): string {
        const h = Md5.hashStr(str);
        return h;
    }
    
    // component.ts
    this.hash = this.hashService.generate(this.form.value.password);
    

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 2021-08-23
      • 2020-07-06
      • 2018-09-17
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多