【发布时间】: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