以下是我的component.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();
});
}
}
res在google sheet服务中返回一个值数组并在控制台上打印出来但在我的组件中订阅时返回undefined(即照片在控制台上返回undefined)。
getImages()
调用从Google电子表格中检索数据的API。
当我尝试将照片分配给portfolioList
变量时,原子突出显示以下错误"Type 'void' is not assignable to type 'string[]' "
。它是有道理的,因为它们是不同的类型,照片不能分配给变量,但我似乎无法解决这个问题以及如何解决这个问题。
非常感谢任何建议或指示。
答案 0 :(得分:3)
您应该在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");
}
修改强>
箭头功能可以有一个简洁的身体&#34;
var fun = z => z + z; //In a concise body, only an expression is needed,and an implicit return is attached.
或通常&#34;阻止身体&#34;。
var fun = (x,y) => { return x + y;}; // In a block body, you must use an explicit return statement.
由于你的函数是&#34;阻止正文&#34;,你必须使用显式的return语句。