【问题标题】:Angular 2 search using httpAngular 2 使用 http 进行搜索
【发布时间】:2016-11-14 03:14:21
【问题描述】:

我有几个组件,一个是获取数据并将其呈现给 dom,另一个是进行搜索 API 调用并将搜索到的数据呈现为第一个组件视图。我附上了图片以获得更清晰的视图:

所以我在这里面临的问题是搜索我需要将搜索到的数据传递给父组件以便它可以呈现它,我为此使用输入/输出,下面是我的代码:

// SpreadSheet Component - Component 1
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Http, HTTP_PROVIDERS, Headers, Response } from "@angular/http";
import { Observable } from 'rxjs/Rx';
import { ContactService } from '../../services/contactService';

@Component({
  selector: 'spreadsheet',
  pipes: [],
  providers: [ContactService],
  directives: [],
  styleUrls: ['./spreadsheet.css'],
  templateUrl: './spreadsheet.html',
  inputs: ['contactlist']
})
export class Spreadsheet {
  public contactlist = [];
  public sortOrder = 'asc';
  public editDisabled = true;
  sortCol = 'name_given';
  toggle = false;
  defaultPage = 0;
  defaultPageSize = 20;
  pageNumber = this.defaultPage
  pageSize = this.defaultPageSize;

  constructor(private contactService: ContactService) {}

  ngOnInit() {
    this.getContacts();
  }

  getContacts(sorting = false) {
    this.contactService.getName(this.pageNumber, this.pageSize, this.sortCol, this.sortOrder)
      .subscribe(
        data => { 
          if(!this.contactlist.length || sorting) {
            this.contactlist = data.results;  
          } else {
            for (let contact of data.results) {
              this.contactlist.push(contact);
            }
          }
        },
        err => console.error(err),
        () => console.log('Contact list fetched...')
      );
  }
}

// Search Component - Component 2
import { Component, Input } from '@angular/core';
import { Http, HTTP_PROVIDERS, Headers, Response } from "@angular/http";
import { Observable } from 'rxjs/Rx';
import { ContactService } from '../../services/contactService';
import { Spreadsheet } from '../spreadsheet/spreadsheet.component';

@Component({
  selector: 'searchForm',
  pipes: [],
  providers: [ContactService],
  directives: [Spreadsheet],
  styleUrls: ['./search.css'],
  templateUrl: './search.html'
})
export class Search {
  searchedList = [];
  constructor(private contactService: ContactService) {}

  searchContact(searchKey) {
    this.contactService.searchContact(searchKey)
      .subscribe(
        data => { 
          this.searchedList = data.results;
        },
        err => console.error(err),
        () => console.log('Search result fetched...')
      );
  }
}

现在在 search.html 中将搜索结果数据传递给父组件我正在这样做:

<form class="form-inline pull-xs-right">
    <input class="form-control" type="text" [(ngModel)]="searchKey" placeholder="Search">
    <button class="btn btn-success-outline" type="submit" (click)="searchContact(searchKey)">Search</button>
</form>
<spreadsheet [contactlist]="searchedList"></spreadsheet>

现在这里的问题是我的电子表格视图呈现了两次,因为我在搜索组件中,一次是使用路由。那么有什么方法可以阻止搜索呈现,它应该呈现第一个组件视图并在那里更新数据。

或者有没有其他方法可以实现从一个组件到另一个组件的数据变化

【问题讨论】:

  • 我不太明白这里的问题。
  • 该联系人表将可见两次,首先来自搜索组件,其他来自自身组件(电子表格),搜索结果将仅在搜索组件表上生效,因此这里应该只有一个表可见(电子表格组件表不搜索)
  • 或者有没有其他方法可以从其他组件更新一个组件变量?不使用输入输出
  • 所以你要做的是找到一种方法将数据隧道传输到原始表,这样你就不会有两组数据了。
  • 对,我猜在这种情况下输入输出不会有帮助吧?

标签: angularjs angular angular2-template


【解决方案1】:

所以你想要做的是在你的服务中有一个 rxjs 主题。

private _contactObject = new Subject < any > ();
contactDataAnnounced$ = this._contactObject;

当您调用 ContactService 时,您将利用它在两个组件之间同步数据。

// SpreadSheet Component - Component 1
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Http, HTTP_PROVIDERS, Headers, Response } from "@angular/http";
import { Observable } from 'rxjs/Rx';
import { ContactService } from '../../services/contactService';

@Component({
  selector: 'spreadsheet',
  pipes: [],
  providers: [ContactService],
  directives: [],
  styleUrls: ['./spreadsheet.css'],
  templateUrl: './spreadsheet.html',
  inputs: ['contactlist']
})
export class Spreadsheet {
  public contactlist = [];
  public sortOrder = 'asc';
  public editDisabled = true;
  sortCol = 'name_given';
  toggle = false;
  defaultPage = 0;
  defaultPageSize = 20;
  pageNumber = this.defaultPage
  pageSize = this.defaultPageSize;

  constructor(private contactService: ContactService) {
     // You can subscribe here to the subject in your service to know when new data has been pushed.
     let self = this;
     this.contactService.contactDataAnnounced$.subscribe(contact =>{
        self.contactlist = contact;
     });
  }

  ngOnInit() {
    this.getContacts();
  }

  getContacts(sorting = false) {
    this.contactService.getName(this.pageNumber, this.pageSize, this.sortCol, this.sortOrder)
      .subscribe(
        data => { 
          if(!this.contactlist.length || sorting) {
            this.contactlist = data.results;  
          } else {
            for (let contact of data.results) {
              this.contactlist.push(contact);
            }
          }
          // Will send this contact list to the search component also because it is subscribed to the _contactObject subject.
          this._contactObjectnext(this.contactList);
        },
        err => console.error(err),
        () => console.log('Contact list fetched...')
      );
  }
}

// Search Component - Component 2
import { Component, Input } from '@angular/core';
import { Http, HTTP_PROVIDERS, Headers, Response } from "@angular/http";
import { Observable } from 'rxjs/Rx';
import { ContactService } from '../../services/contactService';
import { Spreadsheet } from '../spreadsheet/spreadsheet.component';

@Component({
  selector: 'searchForm',
  pipes: [],
  providers: [ContactService],
  directives: [Spreadsheet],
  styleUrls: ['./search.css'],
  templateUrl: './search.html'
})
export class Search {
  searchedList = [];
  constructor(private contactService: ContactService) {
      let self = this;
      this.contactService.contactDataAnnounced$.subscribe(search=>{
        self.searchedList = search;
      });
  }

  searchContact(searchKey) {
    this.contactService.searchContact(searchKey)
      .subscribe(
        data => { 
          this.searchedList = data.results;
          this._contactObject.next(this.searchList)
        },
        err => console.error(err),
        () => console.log('Search result fetched...')
      );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2016-12-06
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    相关资源
    最近更新 更多