【发布时间】:2017-03-28 21:15:50
【问题描述】:
我在标题组件中有一个搜索栏。
在此之下,我在同一个组件中有一个“路由器插座”。
搜索栏(输入文本字段),一旦按下回车,需要发送搜索字符串(event.target.value)到驻留在它下面的路由器出口中的组件,以便它可以运行一个方法来返回结果。
我不知道实现这一目标的最佳方法是什么。
已更新代码..
app.component.html:
<div class="white-container">
<input name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchCourse($event)">
</div>
<router-outlet></router-outlet>
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { CourseService } from './services/courses.service';
import { Course } from './Course';
@Component({
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [CourseService]
})
export class AppComponent implements OnInit {
constructor(private _courseService: CourseService) {
}
searchCourse(event) {
// the user search string here...
}
}
/course-listings/course-listings.component.ts:
import { Component, OnInit } from '@angular/core';
import { CourseService } from './services/courses.service';
import { Course } from './Course';
@Component({
selector: 'app-course-listings',
templateUrl: './course-listings.component.html',
styleUrls: ['./course-listings.component.css'],
providers: [CourseService]
})
export class AppComponent implements OnInit {
course: Course[];
constructor(private _courseService: CourseService) {
}
searchCourse(evt) {
// This works once it's fired...
this._courseService.findCourse(evt)
.subscribe(courses => {
this.course = courses;
});
}
}
/services/courses.service.ts:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CourseService {
constructor(private _http:Http) {
}
getCourses(search) {
return this._http.get('/api/v1/courses/'+search)
.map(res => res.json());
}
}
发现问题
Günter Zöchbauer 是正确的。我使用了一个带有 subscribe 和 observables 的服务来做到这一点。谢谢。
【问题讨论】:
-
您能否更具体一些并在此处或 plunkr 中添加您的代码?这样会更好
-
我用代码更新了原帖。 Gunter 正在逃避使用服务,老实说,我不确定如何根据提供的链接集成我需要的东西......下面的人建议添加一个路由器事件侦听器。我不确定是哪个。希望有人能帮忙,谢谢。
-
我设法集成了一个服务,以便它将用户输入从主 app.component 传递到 course-listings 组件视图中的 {{ searchStr }} 属性。我不明白的是,我如何调用显示结果所需的方法当订阅被调用(或者更确切地说,当执行新搜索时)。
-
我做到了!我意识到我必须将代码放在我之前的函数“searchStr”中,在构造函数的订阅中:this.subscription = this._interactionService.searchStr$.subscribe(//listings stuff here)