[英]return observable from angular service
我正在使用角度服务通过Httpclient获取数据并填充数组并将数组返回到组件。 我认为我应该使用可观察的,但我不知道该怎么做。 到目前为止,这是我的代码“我的component.ts”
import { ZoomService } from './../services/zoom.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
providers: []
})
export class HomePage implements OnInit{
constructor(private zoom: ZoomService) {
}
spots: string[] = [];
ngOnInit() {
this.zoom.dosomthing();
//here I try to access the spot array in the service. but it is empty!
this.spots = this.zoom.spots;
//if I log the spots here it is an empty array!
console.log(this.spots);
}
}
这是我的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as $ from 'jquery';
@Injectable({
providedIn: 'root'
})
export class ZoomService {
spots: string[] = [];
constructor(private httpService: HttpClient) {
}
dosomthing() {
this.httpService.get('./assets/plates/plate1/spot.json').subscribe(data
=> {
this.spots = data as string[];
const spots = this.spots;
//here the spot array is not empty!
console.log(this.spots);
});
}
}
在这里,这就是您应该这样做的方式。
//component
import { ZoomService } from './../services/zoom.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{
spots: string[] = [];
constructor(private zoom: ZoomService) {}
ngOnInit() {
this.zoom.dosomthing()
.subscribe((res: string[]) => {
this.spots = res;
console.log(this.spots);
});
}
}
//service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as $ from 'jquery';
@Injectable({
providedIn: 'root'
})
export class ZoomService {
constructor(private httpService: HttpClient) {}
dosomthing(): Observable<string[]> {
return this.httpService.get<string[]>('./assets/plates/plate1/spot.json');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.