typescript - Angular - map 不是一個函數
我正在嘗試在我的 Angular 項目中過濾一個 Observable,但它顯示:“... .map 不是一個函數”,所以,你能解釋一下我的代碼哪裡出問題嗎?
tasks.component.ts (map 也從 rxjs/operators 導入)
ngOnInit() {
this.tasks = this.tasksService.tasks.map(x => x.filter(y => y.isDone == this.completed));
this.tasksService.getTasks();
}
這是提供 Observable 的我的服務:
task.service.ts
export class TasksService {
private _tasks = new BehaviorSubject<Task[]>([]);
tasks = this._tasks.asObservable();
constructor(private http : Http) {
console.log('Tasks Service is initialized...');
}
getTasks() {
this.http.get(URL).subscribe(x => {
this._tasks.next(x.json());
});
}
答案#1
如果你使用的 rxjs 版本低於 6,請這樣導入 map。
import 'rxjs/add/operator/map';
如果你使用的是 rxjs 6 版本或更高版本,那麼首先你必須像這樣導入運算子:
import { map } from 'rxjs/operators';
其次,你必須在 map 之前使用 pipe:
this.tasks = this.tasksService.tasks.pipe(
map(x => x.filter(y => y.isDone == this.completed))
);
答案#2
Using Observable.subscribe directly should work.like below
@Injectable()
export class HallService {
public http:Http;
public static PATH:string = 'app/backend/'
constructor(http:Http) {
this.http=http;
}
getHalls() {
// ########### No map
return this.http.get(HallService.PATH + 'hall.json');
}
}
export class HallListComponent implements OnInit {
public halls:Hall[];
/ *** /
ngOnInit() {
this._service.getHalls()
.subscribe(halls => this.halls = halls.json()); // <<--
}
}
