2017-07-08 110 views
0

值這裏是我的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[]' "。這是有道理的,因爲它們是不同的類型,照片不能分配給變量,但我似乎無法繞過這個問題,我怎麼可以去解決這個問題。

任何建議或指示,非常感謝。

回答

2

您應該返回的結果中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語句。

+0

hi Shanil。你是對的!加入退貨解決了問題!但不使用箭頭函數表示返回?我是否理解錯誤地使用箭頭函數? – eugeneoei

+0

@eugeneoei不,它不。不使用括號'{}'表示返回。例如:'.map((res:Response)=> res.json());' – echonax

+1

@echonax ahhhhh。我現在明白了。這樣一個根本的錯誤。感謝echonax和@Shanil! – eugeneoei