![](/img/trans.png)
[英]Fetching data from json file via service is giving “unexpected end of input” in Angular4
[英]How to return data from service in angular4
來自Angular1x背景。我正在將現有應用遷移到Angular4
這就是我的ng4服務的樣子
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
@Injectable()
export class DataService {
private _http : Http;
constructor(http:Http) {
this._http = http;
}
public GetPosts() : any{
this._http.get("https://jsonplaceholder.typicode.com/posts").subscribe(data => {
const posts = data.json();
console.log(posts); // logs the desired json
return posts;
})}}
從組件消耗以上服務。
import { Component, OnInit } from '@angular/core';
import {Customer} from './customer.model';
import {DataService } from '../../providers/data.service';
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
private _dService: DataService;
constructor(dService:DataService) {
this._dService = dService;}
ngOnInit() {}
public GetAll(){
let posts =this._dService.GetPosts();
debugger;
console.log(posts); // undefined
/* here the posts is getting UNDEFINED (error) */
}}
在Angular1X中,我曾經從ngService返回Promise,但是在angular4中該怎么做?
您應該在組件而非服務中訂閱可觀察對象。
為您服務
public GetPosts() : any{
return this._http.get("https://jsonplaceholder.typicode.com/posts");
}
在你的組件中
this._dService.GetPosts().subscribe(data => {
const posts = data.json();
console.log(posts);
// Do whatever you like with posts
)};
訂閱調用應在組件代碼中
constructor(private http:Http) { }
getPosts(){
return this.http.get('https://jsonplaceholder.typicode.com/posts').map(
(response: Response) => {
return response.json();
}
)
}
在組件中:您聲明的最佳做法:
data : any;
this._dService.GetPosts().subscribe(
data => {this.data = data;
console.log(this.books);},
err => {console.log(err);},
()=> {console.log("terminated");}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.