函数返回不需要的数据

时间:2018-11-20 13:07:46

标签: angular typescript

我有一个JSON文件,其中包含一些跑步者的数据。 我正在尝试使用以下方法过滤一些数据:

performFilterByRunnerName(filterBy: string):IRunners[]{
    return this.runners.filter(x=>x.runnerName=filterBy);
}

HTML的一部分是:

<input #filterinputrunner id="runnerFilter" type="text" 
  (change) = "performFilterByRunnerName(filterinputrunner.value)"
  [ngModel]='listRunnerFilter'>

我有一个IRunner类型(接口)的列表,其中包含跑步者的数据。 更改input的值时,发生的情况是runnerName字段对所有runners都发生了更改,而不是使用输入值过滤运行器。 我在做什么错了?

4 个答案:

答案 0 :(得分:2)

    #-------- COPY PASTED BigQueryGetDataOperator SECTION: START --------------
    '''Source: https://airflow.readthedocs.io/en/stable/_modules/airflow/contrib/operators/bigquery_get_data.html#BigQueryGetDataOperator '''

    from airflow.contrib.hooks.bigquery_hook import BigQueryHook
    from airflow.models import BaseOperator
    from airflow.utils.decorators import apply_defaults


    class BigQueryGetDataOperator(BaseOperator):
        template_fields = ('dataset_id', 'table_id', 'max_results')
        ui_color = '#e4f0e8'

        @apply_defaults
        def __init__(self,
                     dataset_id,
                     table_id,
                     max_results='100',
                     selected_fields=None,
                     bigquery_conn_id='bigquery_default',
                     delegate_to=None,
                     *args,
                     **kwargs):
            super(BigQueryGetDataOperator, self).__init__(*args, **kwargs)
            self.dataset_id = dataset_id
            self.table_id = table_id
            self.max_results = max_results
            self.selected_fields = selected_fields
            self.bigquery_conn_id = bigquery_conn_id
            self.delegate_to = delegate_to

        def execute(self, context):
            self.log.info('Fetching Data from:')
            self.log.info('Dataset: %s ; Table: %s ; Max Results: %s',
                          self.dataset_id, self.table_id, self.max_results)

            hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id,
                                delegate_to=self.delegate_to)

            conn = hook.get_conn()
            cursor = conn.cursor()

    #----------------------- COPY PASTED SECTION: END ----------------

        # Trying to add to a MongoDB here itself - coed by GT
        from pymongo import MongoClient
        header = ['day', 'ticker','app_id','area', 'store_types', 'devices_in_store', 'devices_in_store_or_plot', 'matched_devices', \
'all_devices']
        client = MongoClient('35.237.46.25:27017')
        db = client.test03
        collection = db.advan_t1_sample_mongo00

        response = cursor.get_tabledata(dataset_id=self.dataset_id, start_index=0,
                                        table_id=self.table_id,
                                        max_results='2',
                                        selected_fields=self.selected_fields)
        total_rows=int(response['totalRows'])
        chunksize=100000
        for chunk in range(0,total_rows,chunksize):
          rows=[]
          if chunk+chunksize<total_rows:
            self.log.info("Extracting chunk %d to %d"%(chunk,chunk+chunksize))
            response = cursor.get_tabledata(dataset_id=self.dataset_id, start_index=chunk,
                                        table_id=self.table_id,
                                        max_results=str(chunksize),
                                        selected_fields=self.selected_fields)

            rows = response['rows']

            for row in rows:
              onerow={}
              for i,f in zip(range(len(row['f'])),row['f']):
                onerow[header[i]] = f['v']
              collection.insert_one(onerow)
            self.log.info("------------------------- Document size: %d --------------------"%(collection.find().count()))
          else:
            self.log.info("Extracting chunk %d to %d"%(chunk,total_rows))
            response = cursor.get_tabledata(dataset_id=self.dataset_id, start_index=chunk,
                                        table_id=self.table_id,
                                        max_results=total_rows,
                                        selected_fields=self.selected_fields)

            rows = response['rows']

            for row in rows:
              onerow={}
              for i,f in zip(range(len(row['f'])),row['f']):
                onerow[header[i]] = f['v']
              collection.insert_one(onerow)
            self.log.info("------------------------- Document size: %d --------------------"%(collection.find().count()))


        self.log.info("Pushed into %s"%collection.name)

        if total_rows == collection.find().count():
          self.log.info("Successfully pushed %d records into %s"%(total_rows,collection.name))
          return(1)
        else:
          self.log.warning("Push Failed! Total Rows: %d Document Size: %d"%(total_rows,collection.find().count()))
          return(0)
#        return rows

    from airflow import models
    from airflow.operators.python_operator import PythonOperator
    from airflow.utils import trigger_rule
    from airflow.contrib.operators import gcs_to_bq
    from airflow.contrib.operators import bigquery_to_gcs
    from airflow.contrib.operators import bigquery_operator
    from airflow.contrib.operators import bigquery_get_data
    from airflow.contrib.operators import MongoHook
    def get_dlist(**kwargs):
      import logging as log
      #Import pymongo
      from pymongo import MongoClient
      #Pull the data saved in XCom
      value = kwargs.get('task_instance').xcom_pull(task_ids='get_data_in_list_from_bq')

      header = ['V1','V2']
      data=[]
      for rows in value:
        onerow={}
        for i,f in zip(range(len(rows['f'])),rows['f']):
          onerow[header[i]] = f['v']
        data.append(onerow)
      log.info("Pulled...")
      log.info(data)
      log.info("Pushing into mongodb...")
      client = MongoClient(localhost:27017)
      db = client.test
      collection = db.testingbq2mongo
      collection.insert(data)
      log.info("Written to mongoDB...")
      client.close()

    default_dag_args = {
        # Setting start date as yesterday starts the DAG immediately when it is
        # detected in the Cloud Storage bucket.
        'start_date':yesterday,
        # To email on failure or retry set 'email' arg to your email and enable
        # emailing here.
        'email_on_failure': False,
        'email_on_retry': False,
        # If a task fails, retry it once after waiting at least 5 minutes
        'retries': 0,
        #'retry_delay': datetime.timedelta(minutes=5),
        'project_id': 'data-rubrics'
    }

    try:
      # [START composer_quickstart_schedule]
      with models.DAG(
            'composer_testing00',
            # Continue to run DAG once per day
            schedule_interval=datetime.timedelta(days=1),
            default_args=default_dag_args) as dag:
        # [END composer_quickstart_schedule]

      data_list = bigquery_get_data.BigQueryGetDataOperator(\
    task_id='get_data_in_list_from_bq',\
    dataset_id='testcomposer',\ # Name of the dataset which contains the table ( a BQ terminology)
    table_id='summarized_sample_T1' # Name of the BQ table you want to push into MongoDB
    )

      op_push2mongo = PythonOperator(task_id='Push_to_MongoDB', python_callable=get_dlist, provide_context=True)
      data_list >> op_push2mongo
    except Exception as e:
      raise(e)

您要比较而不是分配

(x=>x.runnerName=filterBy)

应该是正确的。投票关闭。

答案 1 :(得分:1)

您的过滤条件似乎不正确。您正在为每个跑步者分配(=属性filterBy

您想要的是相等条件(===)。

return this.runners.filter(x => x.runnerName === filterBy);

答案 2 :(得分:1)

此行突出显示的代码是在分配值而不是对其进行比较。

  

返回this.runners.filter(x => x.runnerName = filterBy

您需要进行以下比较:

return this.runners.filter(x=>**x.runnerName === filterBy**) 

答案 3 :(得分:1)

如果您使用的是change,它将不会在您键入时更新过滤的结果,而只会在blur上对其进行更新。如果您希望在键入时更新列表,则应考虑使用keyup

(keyup) = "performFilterByRunnerName(filterinputrunner.value)"

此外,基于过滤器搜索的过滤器将包括在结果中,而不是确切的字符串搜索。这样会产生更好的搜索结果:

onFilterChange(filterBy) {
  this.filteredUsers = [...this.users.filter(user => user.name.indexOf(filterBy) > -1)];
}

这是您推荐的Sample StackBlitz