возврат наблюдаемого из угловой службы - PullRequest
0 голосов
/ 17 января 2019

Я использую угловой сервис, чтобы получать данные через Httpclient, заполнять массив и возвращать массив компоненту. Я думаю, что я должен использовать наблюдаемые, но я не могу понять, как это сделать. вот мой код пока my 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); 
});
}
}

1 Ответ

0 голосов
/ 17 января 2019

Вот как вы должны это сделать.

//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');
    }
}
...