2016-09-17 84 views
4

我訪問變量時遇到問題,應該通過服務解決。如果我在html中直接使用這個變量是沒有問題的,但是當我想在方法中使用它時,我什麼也沒有。服務工作正常,它是http休息服務電話。 這裏的控制器:Typescript應該通過服務傳遞的角度訪問參數

​​

,服務是這樣的:

/// <reference path='../_app.ts' /> 
    module domain { 
import DocumentEntity = domain.DocumentEntity; 

export interface IDataAccessService { 
    getDataResource(): ng.resource.IResourceClass<IEntityResource>; 
} 

export interface IEntityResource extends ng.resource.IResource<domain.Entity> { 
} 

export class DataAccessService implements IDataAccessService { 
    //minification protection 
    static $inject = ["$resource"] 

    constructor(private $resource: ng.resource.IResourceService) { 
     console.log("DataAccessService Constructor"); 
    } 

    getDataResource(): ng.resource.IResourceClass<IEntityResource> { 
     console.log("REST CALL"); 
     return this.$resource("http://localhost:8080/services/name/:searchId/documents/", {searchId: "12345678"}, { 
      'query': { 
       method: 'GET', 
       isArray: false 
      } 
     }); 
    } 
} 

angular.module("common.services", ["ngResource"]); 
} 

回答

0

我在$控制器的構造函數替換部分promise.then構造是這樣的:

documentResource.query((data: domain.IEntity) => { 
      this.response = data; 
     }).$promise.then((data)=> { 
       if (this.response.folders) { 
        this.structures = []; 
        for (let i = 0; i < this.response.folders.length; i++) { 
         if(this.response.folders){ 
         Array.prototype.push.apply(this.structures,this.createFolderStructure(this.response.folders, 4)); 
         } 
        } 
        console.log(this.structures); 
       } 
      } 
     ); 
0

雖然你以正確的方式解決了這個問題,我想指出真正的問題。真正的問題是你沒有在第一個參數的查詢請求中傳遞查詢參數。您應該將第一個參數作爲{}傳遞給query函數,然後我們可以通過成功&錯誤回調第二個& 3rd。

代碼

var documentResource = dataAccessService.getDataResource(); 
documentResource.query({}, //1st parameter should pass as a blank 
    (data: domain.IEntity) => { 
    this.response = data; 
    } 
); 

雖然另一種方式是,你可以直接分配$resource承諾對象所需的變量,所以當承諾得到解決API將解開這一承諾和接收的數據分配給this.response

this.response = dataAccessService.getDataResource(); 
+0

對不起,我在源代碼中有這個參數,但是在編輯這個帖子的實際URL時我刪除了它。我將編輯我的帖子。 – Ladislav

+0

我仍然沒有看到它.. –