我从angular.io网站使用以下代码。为了获得搜索observables。Angular2 - 为什么主题的实例被放置在ngOninit中?
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-dropdown-suggestion',
templateUrl: './dropdown-suggestion.component.html',
styleUrls: ['./dropdown-suggestion.component.css']
})
export class DropdownSuggestionComponent implements OnInit {
userSuggestions: Observable<User[]>;
userSuggestionsLoad: Subject<string> = new Subject<string>();
constructor(protected apiService: ApiService,) { }
ngOnInit() {
this.userSuggestions = this.userSuggestionsLoad
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => this.apiService.search(term))
.catch(error => {
console.log(error);
return Observable.of<User[]>([]);
});
}
searchUsers(term) {
const url = this.url + term ;
this.userSuggestionsLoad.next(url);
}
我想知道为什么this.userSuggestionsLoad
放在ngOninit
总是内,如果我把这个之外这是行不通的。
我想了解这一点,因为我想将此功能作为基本组件,并且希望将此组件扩展到其他组件中。但在这种情况下,this.userSuggestionsLoad
未被触发,可能是因为ngOninit
。
张贴链接到您在哪里找到代码的地方 –
https://v2.angular.io/docs/ts /latest/tutorial/toh-pt6.html –