在服务文件中致电Web服务,并在其他地方重复使用



我需要在应用程序的其他部分重新使用服务功能,更具体地说是在html模板中显示某个参数(在我的情况下为'title')。p>因此,我基本上创建了一个服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserInfoService {
loading: boolean;
dataSet = [];
constructor(public http: HttpClient) { 
 this.getList();
}
getList(){
  this.loading = true;
  this.http.get('https://jsonplaceholder.typicode.com/posts')
  .subscribe(data => {
  this.dataSet = [data];
  this.loading = false;
  });
}}

然后我有一个导入上述服务的组件:

import { Component, OnInit } from '@angular/core';
import { UserInfoService } from '../../models/user-info.service';
@Component({
 selector: 'app-user',
 templateUrl: './user.component.html',
 styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
 res = [];
constructor( private UserInfoServiceData:UserInfoService ) { }
ngOnInit() {
this.res = [this.UserInfoServiceData];
}}

最后,在我的HTML模板中,我试图从Web服务中显示"标题"。目前,我得到[对象]。

<p>
    <span *ngFor="let res of res">{{res | json}}</span>
</p>

与可观察的

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class UserInfoService {
loading: boolean;
private dataSetSource = new Subject<any | Error>();
public _dataSet:  Observable<any | Error> = this.dataSetSource.asObservable();

constructor(public http: HttpClient) { 
//try to not put things here if you can
}
getList() {
this.getHTTPList();
 return this._dataForm;
}
private getHTTPList(){
  this.loading = true;
  this.http.get('https://jsonplaceholder.typicode.com/posts')
  .subscribe(data => {
  this.dataSetSource.next(data);
  this.loading = false;
  });
}}

import { Component, OnInit } from '@angular/core';
import { UserInfoService } from '../../models/user-info.service';
@Component({
 selector: 'app-user',
 templateUrl: './user.component.html',
 styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
 res = [];
constructor( private UserInfoServiceData:UserInfoService ) { }
ngOnInit() {
this.UserInfoServiceData.getList().subscribe (
(data: any) => { 
this.res.push(data);
}
);
}}
<p>
    <span *ngFor="let var of res">{{var | json}}</span>
</p>

相关内容

  • 没有找到相关文章

最新更新