订阅值返回undefined在component.ts但存在service.ts
问题描述:
值这里是我的component.ts
文件订阅值返回undefined在component.ts但存在service.ts
import { Component, OnInit } from '@angular/core';
import { GoogleSheetsService } from '../shared/services/googlesheets.service';
@Component({
selector: 'home-component',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
apiPortfolioListEndPoint: string;
portfolioList: Array<string>;
constructor (
private googleSheetsService: GoogleSheetsService
) {}
ngOnInit() {
this.apiPortfolioListEndPoint = '/home/portfolio';
this.getImagesFromSheets(this.apiPortfolioListEndPoint);
}
getImagesFromSheets(sheetName) {
this.googleSheetsService.getImages(sheetName)
.subscribe(photos => {
console.log(photos);
});
}
}
和我service.ts
文件的内容的内容
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class GoogleSheetsService {
constructor(
private http: Http
) { }
getImages(sheetName) {
const apiServerEndPoint = '/api' + sheetName;
return this.http.get(apiServerEndPoint)
.map((res: Response) => {
console.log(res.json());
res.json();
});
}
}
资源在谷歌表服务返回一个值的数组,并在控制台上打印出来,但在我的组件中订阅时返回undefined(即照片在控制台上返回undefined)。
getImages()
调用从Google电子表格中检索数据的API。
当我试图将照片分配给portfolioList
变量时,atom会突出显示以下错误"Type 'void' is not assignable to type 'string[]' "
。这是有道理的,因为它们是不同的类型,照片不能分配给变量,但我似乎无法绕过这个问题,我怎么可以去解决这个问题。
任何建议或指示,非常感谢。
答
您应该返回的结果中map
getImages(sheetName) {
const apiServerEndPoint = '/api' + sheetName;
return this.http.get(apiServerEndPoint)
.map((res: Response) => {
console.log(res.json());
/* You need to return the data here*/
return res.json();
});
}
更妙
/* import these first*/
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
getImages(sheetName) {
const apiServerEndPoint = '/api' + sheetName;
return this.http.get(apiServerEndPoint)
.map(this.extractData)
.catch(this.catchError);
}
private extractData(res: Response) {
return res.json();
}
private catchError(error: Response | any) {
return Observable.throw(error.json().error || "Server Error");
}
编辑
箭功能可以有一个 “简明体”
var fun = z => z + z; //In a concise body, only an expression is needed,and an implicit return is attached.
或通常的“块体”。
var fun = (x,y) => { return x + y;}; // In a block body, you must use an explicit return statement.
由于你的函数是“块体”,你必须使用显式的return语句。
hi Shanil。你是对的!加入退货解决了问题!但不使用箭头函数表示返回?我是否理解错误地使用箭头函数? – eugeneoei
@eugeneoei不,它不。不使用括号'{}'表示返回。例如:'.map((res:Response)=> res.json());' – echonax
@echonax ahhhhh。我现在明白了。这样一个根本的错误。感谢echonax和@Shanil! – eugeneoei