2017-10-10 52 views
0

我是Angular2的新手,對我很袒護。我有一個DataService應該獲得文本框的值,並將其傳遞到我的組件。我想知道是否有一種方法來訪問我的index.html文件中的文本框值更改時的服務對象?這是我到目前爲止已經試過:Angular2在index.html中訪問服務對象

的DataService:

export interface Info{ 
    itemNo:string; 
} 

@Injectable() 
export class DataService { 

item:Info={itemNo:"Test"}; 

change(newItem:string){ 
    this.item.itemNo=newItem; 
} 
constructor(private http: Http) { } 
} 

我想從業務接入改變方法:

onSelect: function (request, response) { 
    console.log(urlApi); 
      $.ajax({ 
       type: "GET", 
       url: urlApi, 
       dataType: 'json', 
       success: function(response) { 
        this.item.change(response.items[0].item); //This is what I am trying to do 
       }, 
       error: function() { alert('Failed!'); }, 
      }); 
     } 

有人能指出我怎麼能做到這一點?

回答

0

我認爲你的問題是與「這個」範圍。如果您可以使用ES6,則可以使用新的arrow functions訪問此項目。它可能和...一樣簡單。

... 
 
success: (response) =>{ 
 
    this.item.change(response.items[0].item); //This is what I am trying to do 
 
} 
 
...

雖然說了這麼多,你可能採用了棱角分明的HTTP client而不是jQuery的

會更好