我從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 –