2017-05-01 26 views
0

我想通過點擊來更新服務。如何在angular2上點擊更新服務json或數組值?

  • 服務

    import { Injectable } from '@angular/core'; 
    @Injectable() 
    export class ImageoptionsService { 
    
    publicImageOption() { 
        return { 
         imgoptions: { 
         thumbBox: '.thumbBox', 
         spinner: '.spinner', 
         imgSrc: './assets/background/one.jpg' 
        } 
        } 
    } 
    constructor() { } 
    
    } 
    

而且在我稱之爲這是工作的罰款的組件。現在我想通過點擊一個元素來更新它的'imgoptions'值。

  • mycomonent.component.ts

    import { Component, OnInit } from '@angular/core'; 
    import { ImageoptionsService } from "../imageoptions.service"; 
    
    @Component({ 
        selector: 'app-bglist', 
        templateUrl: './bglist.component.html', 
        styleUrls: ['./bglist.component.css'] 
    }) 
    
    export class mycomonent implements OnInit { 
        public backgrounds = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; 
        constructor(private imageservice: ImageoptionsService) { } 
        changebg(index) { 
        } 
    ngOnInit() { 
    } 
    
    } 
    
  • mycomonent.component.html

    <ul class="imagelist"> 
         <li class="bgimage" *ngFor="let background of backgrounds; let imgi = index" (click)="changebg(imgi)"> 
         <img src="./assets/background/{{background}}.jpg" alt="{{background}}" /> 
        </li> 
        </ul> 
    

從上面的例子,我想改變在 'imgoptions' 值服務通過調用'changebg(index){}'這個函數。

請讓我知道是否有任何方法來執行此操作。

感謝

回答

1

解決方案如下附:

第1步:

添加一個setter方法在ImageoptionsService服務,將更新您的業務數據。

import { Injectable } from '@angular/core'; 
@Injectable() 
export class ImageoptionsService { 

private data = { 
     imgoptions: { 
     thumbBox: '.thumbBox', 
     spinner: '.spinner', 
     imgSrc: './assets/background/one.jpg' 
     } 
} 

publicImageOption() { 
    return this.data; 
} 

updateData() { 
    // put your logic to update this.data 
} 

} 

第二步:

使用此方法對服務實例時,事件回調被調用:

import { Component, OnInit } from '@angular/core'; 
import { ImageoptionsService } from "../imageoptions.service"; 

@Component({ 
    selector: 'app-bglist', 
    templateUrl: './bglist.component.html', 
    styleUrls: ['./bglist.component.css'] 
}) 

export class mycomonent implements OnInit { 
    public backgrounds = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; 
    constructor(private imageservice: ImageoptionsService) { } 

    changebg(index) { 
    // invoking updateData method to update service data 
    this.imageservice.updateData(); 
    } 

ngOnInit() { 
    } 

} 

乾杯!

+0

謝謝@Suneet,它的工作完美:) –

相關問題