我正在尝试通过将JobService
jobs:Job[]
变量分配给请求的结果来将HTTP结果缓存到本地变量中。然后,我希望从注入setSearch()
的另一个组件中过滤调用JobService
函数的结果。
当UserService
检索用户时,JobService
订阅该事件并获取作业。这意味着如果用户状态发生变化,那么jobs数组也会发生变化。然后,它会调用setJobs()
来设置本地jobs
变量
稍后当用户在搜索框中输入内容时,setSearch()
会被调用,而this.jobs
是一个空数组,即使它已在setJobs()
中设置
jobsPublisher
然后将这组新作业发布给订阅者。
注意:HttpCacheService
与Http
非常相似,但它只是将响应映射到所需的对象,同时处理和记录错误。
@Injectable()
export class JobService {
jobsPublisher: BehaviorSubject<Job[]>
private jobs: Job[] = []
constructor(
private http: HttpCacheService<Job[]>,
private userService: UserService,
private searchService: SearchService
) {
this.jobsPublisher = new BehaviorSubject<Job[]>(this.jobs)
this.userService.userPublisher.subscribe((user: User) => {
this.getJobs()
})
}
private getJobs(): void {
let req = this.http.GET("/d/jobs").subscribe(jobs => {
this.setJobs(jobs) // jobs = Array(100)
this.jobsPublisher.next(jobs)
req.unsubscribe()
})
}
private setJobs(jobs) {
console.log("Setting jobs!")
this.jobs = jobs // this.job = jobs = Array(100)
}
setSearch(query: string) { // this.jobs = []
let newJobs = this.filterJobs(query, this.jobs)
console.log(`Job Length Filter [${this.jobs.length}] -> [${newJobs.length}]`)
this.jobsPublisher.next(newJobs)
}
private filterJobs(query: string, jobs: Job[]): Job[] {
// Filter jbos
}
}
export class JobsListComponent implements OnInit {
public jobrows: Array<Array<Job>> = []
constructor(private jobService: JobService, private searchService: SearchService) { }
ngOnInit() {
this.jobService.jobsPublisher.subscribe((jobs: Job[]) => {
this.genRows(jobs)
})
}
private genRows(jobs: Array<Job>): void {
this.jobrows = []
while (jobs.length > 0)
this.jobrows.push(jobs.splice(0, 3))
}
search(event: any): void {
this.jobService.setSearch(event.target.value || "")
}
}
答案 0 :(得分:0)
private genRows(jobs: Array<Job>): void {
jobs = jobs || []
this.jobrows = []
while (jobs.length > 0)
this.jobrows.push(jobs.splice(0, 3))
}
是你正在改变数组的罪魁祸首。
将其转换为:
this.jobrows.push(jobs.slice(0, 3))