【问题标题】:This condition will always return 'false' since the types 'string' and '() => string' have no overlap此条件将始终返回 'false',因为类型 'string' 和 '() => string' 没有重叠
【发布时间】:2019-07-03 16:03:18
【问题描述】:

我有一个 JSON 文件,其中包含以下对象数组:https://pastebin.com/raw/prnChamA。数据包含名为 postitoimipaikka 的键,我需要循环这些键,以便仅获取在键 postitoimipaikka 中具有匹配值的对象。

用户输入一个字符串postitoimipaikka作为函数参数,然后用于循环对象的JSON数组。

我在atms.service.ts 中收到以下错误:This condition will always return 'false' since the types 'string' and '() => string' have no overlap

上线:

if (d.postitoimipaikka == postitoimipaikka.toUpperCase) {

atms.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { atm } from '../app/atm.interface';

@Injectable()
export class ATMService {

  constructor(public http: HttpClient) { }

  url = "./assets/data.json";

  searchByMunicipalityName = (municipality: string): Promise<atm[]> => {
    return new Promise((resolve, reject) => {
      this.http.get(this.url).subscribe((data: atm[]) => {
        let list: atm[] = [];
        for (let d of data) {
          if (d.postitoimipaikka == municipality.toUpperCase) {
            lista.push(d);
          }
        }
        resolve(list);
      }, (error) => {
        reject(error);
      })
    })
  }


}

如果toUpperCase方法被删除,用户必须输入大写的字符串,这是不合适的,否则会起作用。

【问题讨论】:

  • 不要忘记通过添加括号来调用方法:postitoimipaikka.toUpperCase()

标签: angular


【解决方案1】:

您的错误是您没有调用toUpperCase,您必须在其后添加括号。此外,您定义了一个名为 list 的数组,但实际上您正在推送到一个名为 lista 的数组。

您可以将代码重构为:

return new Promise((resolve, reject) => {
    this.http.get(this.url).subscribe((data: atm[]) => {
        resolve(data.filter(d => d.postitoimipaikka == municipality.toUpperCase()));
      }, (error) => {
        reject(error);
      })
    })
  }

【讨论】:

    【解决方案2】:

    我更喜欢使用 filter() 从数组中提取对象。我的版本如下:

    searchByMunicipalityName = (municipality: string): Promise<atm[]> => {
        return new Promise((resolve, reject) => {
          this.http.get(this.url).subscribe((data: atm[]) => {
            const list: atm[] = data.filter(x => 
            x.postitoimipaikka === municipality.toUpperCase()); 
            resolve(list);
          }, (error) => {
            reject(error);
          })
        })
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2020-12-11
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多