我正在尝试使用从轮播服务中的json文件检索的数据设置slides []属性。我的轮播组件注入了轮播服务并调用了公共的getSlides()函数,但是返回的值是一个空数组。
我在做什么错了?
此处包含代码:
//carousel.component.ts
import { Component, OnInit } from '@angular/core';
import { CarouselService } from '../../services/carousel.service';
@Component({
selector: 'app-carousel',
templateUrl: './carousel.component.html',
styleUrls: ['./carousel.component.css']
})
export class CarouselComponent implements OnInit {
slides: string[];
constructor(private carouselService: CarouselService) { }
ngOnInit() {
this.getSlides();
}
getSlides(): void {
this.carouselService.getSlides()
.subscribe(slides => {
console.log('show slides', slides);
this.slides = slides
});
}
}
Carousel.service.ts
import { Injectable } from '@angular/core';
import { Observable, of, ObservableInput } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CarouselService {
slides: string[] = [];
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
this.slides = data['Carousel'];
console.log('data loaded');
});
}
public addSlide(title: string) {
this.slides.push(title);
}
public getSlides(): Observable<string[]> {
return of(this.slides);
}
private getJSON(): Observable<Object> {
return this.http.get("./assets/carousel.json");
}
}
答案 0 :(得分:0)
我在注释部分引用了Suryan的建议,并重构了我的代码以使用异步/等待功能,并且在前端,该组件已更新为包括属性。
import { Injectable } from '@angular/core';
import { Observable, of, ObservableInput } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CarouselService {
constructor(private http: HttpClient) { }
async public getJSON(): Observable<Object> {
return this.http.get("./assets/carousel.json");
}
}
//carousel.component.ts
import { Component, OnInit } from '@angular/core';
import { CarouselService } from '../../services/carousel.service';
@Component({
selector: 'app-carousel',
templateUrl: './carousel.component.html',
styleUrls: ['./carousel.component.css']
})
export class CarouselComponent implements OnInit {
slides: string[];
constructor(private carouselService: CarouselService) { }
ngOnInit() {
this.getSlides();
}
getSlides(): void {
this.carouselService.getSlides()
.subscribe(await slides => {
console.log('show slides', slides);
this.slides = slides
}.bind(this));
}
}
请注意,有更好的方法来进行异步操作。我刚刚阅读了Angular.io文档,在那里可以使用async pipes。