【问题标题】:return observable from angular service从角度服务返回可观察的
【发布时间】:2019-01-17 11:09:26
【问题描述】:

我正在使用角度服务通过 Httpclient 获取数据并填充数组并将数组返回给组件。我想我应该使用 observable 但我不知道该怎么做。 到目前为止,这是我的代码” 我的组件.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); 
});
}
}

【问题讨论】:

  • 查看angular.io/guide/http#getting-json-data - Angular 文档非常详细。所以来自/config.service.tsgetConfig() 方法返回Observable。现在在config.component.ts 中的showConfig 方法中订阅它并将响应绑定到组件属性。在您的情况下,data 将是您从服务返回的位置。
  • @AliHaghighi 您的返回类型在哪里 如何从函数dosomthing 获取任何数据?为什么在服务中使用subscribe
  • 如果我不使用服务而不是 this.zoom.dosomthing();我使用此代码 this.httpService.get('./assets/plates/plate1/spot.json').subscribe(data => { this.spots = data as string[]; const spot = this.spots; 但我想要使用服务,以便我的代码可以在其他组件中使用

标签: angular service angular2-observables angular-httpclient


【解决方案1】:

这里,你应该这样做。

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

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2019-12-31
    • 2017-10-03
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多