如何知道Angular 4中的事件发射值已经改变?

时间:2017-09-13 12:58:12

标签: javascript angular typescript observable

我正在开发一个Angular 4应用程序。我有一个搜索组件,用户输入一个字符串。每当用户输入一个值并提交它时,我就会将值从SearchComponent发送到DisplayComponent

在SearchComponent中发布值

@Output() userInput: EventEmitter<string> = new EventEmitter<string>();
onFormSubmit() {
    this.userInput.emit(this.searchForm.value.SearchInputValue);
}

DisplayComponent HTML看起来像

<app-search (userInput)="valueFromSearch"></app-search>
<div class="some-other-html></div>

DisplayComponent TS文件看起来像

valueFromSearch: string;
constructor(private someService: SomeService) {}
ngOnInit() {
    this.someService.getSomeData(valueFromSearch)
       .subscribe((data) => {console.log("Success! data is ",data)},
       (error) => {console.log("Something went wrong", error)})
}

但是,只要someService发生变化,如何运行valueFromSearch函数?我是否应该使用BehaviorSubject来继续监听valueFromSearch

中的更改

是否有任何功能可以知道值已更改?请帮我解决这个问题。

3 个答案:

答案 0 :(得分:0)

你可以使valueFromSearch()成为每次从搜索中发出时调用的方法

  

DisplayComponent HTML

<app-search (userInput)="valueFromSearch(value)"></app-search>
<div class="some-other-html></div>
  

DisplayComponent TS文件

constructor(private someService: SomeService) {}
valueFromSearch(value: string) {
    this.someService.getSomeData(value)
       .subscribe((data) => {console.log("Success! data is ",data)},
       (error) => {console.log("Something went wrong", error)})
}

答案 1 :(得分:0)

ngOnChanges(changes: any) {
    let data = changes.valueFromSearch.currentValue;
    // This only work with a change not if it has the same value.
}

答案 2 :(得分:0)

不确定@ JayDeeEss的方法是否会立即起作用,但稍作修改似乎是可行的。

与他的建议一样,每次valueFromSearch {{1}时,valueFromSearch: string; 方法(从您的组件中移除此声明:userInput)发出一个新值。

  

DisplayComponent HTML(注意传递给EventEmitter的参数的变化;从valueFromSearch()(value)

($event)
  

DisplayComponent TS文件(在组件内部,参数名称不重要)

<app-search (userInput)="valueFromSearch($event)"></app-search>
<div class="some-other-html></div>