简体   繁体   English

角度组件未从角度服务获取数组数据

[英]angular component not getting array data from angular service

I have an angular service which is used as mid point to fetch data from database. 我有一个角度服务,用作从数据库中获取数据的中点。 Here is it: 就这个:

export class WebService {
constructor(private http: Http, private datePipe: DatePipe) {
    this.getStatsbyDate(this.datePipe.transform(new Date(), 'dd-MM-yyyy'));
}
statsModel = {
    date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'),
    answeringMachine:0,
    hangUp: 0,
    conversations: 0
};
getStatsbyDate(date) {
    this.http.get(this.BASE_URL + '/stats/' + date)
      .subscribe(
        res => {
            this.btnsOnResponse = true; 
            this.statsModel = res.json(); 
            // console.log(this.statsModel);                              
        },
        err => {
            console.log("Couldn't fetch data")
        }
    );
}

I am trying to access the fetched data in one of my angular components this way 我正在尝试以这种方式在我的一个角度组件中访问获取的数据

export class FusionChartsComponent implements OnInit {
  constructor(private webService: WebService) {}
  ngOnInit() {
     console.log(this.webService.statsModel.answeringMachine);
  }
}

I am not sure at all why this is happening. 我完全不确定为什么会这样。 Please advise! 请指教!

As shown in the documentation here: https://angular.io/guide/http , move the subscribe to the component. 如此处的文档所示: https : //angular.io/guide/http ,将订阅移至该组件。 Then you can add whatever code you need within the subscribe. 然后,您可以在订阅中添加所需的任何代码。

getStatsbyDate(date) {
    this.http.get(this.BASE_URL + '/stats/' + date)
      .pipe(
        tap(res => {
            this.btnsOnResponse = true; 
            this.statsModel = res.json(); 
            // console.log(this.statsModel);                              
        }),
        catchError(err => console.log("Couldn't fetch data"))
    );
}

export class FusionChartsComponent implements OnInit {
  constructor(private webService: WebService) {}
  ngOnInit() {
     this.webService.getStatsbyDate().subscribe(
         data => {
             console.log(data);
             console.log(this.webService.statsModel.answeringMachine);
     });
  }
}

EDIT 编辑

If you need the service to retain its data to share with other components, you can do something like this: 如果您需要该服务保留其数据以与其他组件共享,则可以执行以下操作:

@Injectable()
export class MovieService {
    private moviesUrl = 'api/movies';
    private movies: IMovie[];

    constructor(private http: HttpClient) { }

    getMovies(): Observable<IMovie[]> {
        if (this.movies) {
            return of(this.movies);
        }
        return this.http.get<IMovie[]>(this.moviesUrl)
                        .pipe(
                            tap(data => console.log(JSON.stringify(data))),
                            tap(data => this.movies = data),
                            catchError(this.handleError)
                        );
    }
}

Each component can subscribe like this: 每个组件都可以这样订阅:

this.movieService.getMovies().subscribe(
    (movies: IMovie[]) => this.movies = movies,
    (error: any) => this.errorMessage = <any>error
);

The first component that calls the service will cause it to send the http get request which will get the data. 调用该服务的第一个组件将使它发送http get请求,该请求将获取数据。 It then stores that data in a private property. 然后,它将数据存储在私有财产中。 All other calls with get the already retrieved data (as shown in the if block). 带有的所有其他调用将获取已检索到的数据(如if块所示)。

Since all of the components are subscribing, you can add whatever code within the subscribe method. 由于所有组件都在订阅,因此您可以在subscribe方法中添加任何代码。 That code will then not execute until it has the data it needs. 该代码直到拥有所需的数据后才会执行。

Most developers consider it to be "best practice" to subscribe as close to the UI as possible. 大多数开发人员认为订阅尽可能接近UI是“最佳实践”。 This also makes it much easier to write code that is only executed after the data is returned. 这也使得编写仅在返回数据后才执行的代码变得容易得多。

I have a complete example of this here: https://github.com/DeborahK/MovieHunter-communication/tree/master/MH-Take4 我在这里有一个完整的示例: https : //github.com/DeborahK/MovieHunter-communication/tree/master/MH-Take4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM