Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 service variable value updating

I can not update my angular service variable value.

I have two non-related components, and i want to send updated object from one to other one , using service . But I can't update object in service.


First component :

import { SoruService } from '../soru.service';
import { SoruModel, SecenekModel } from '../soruModel';

@Component({
    selector: 'app-first',
    templateUrl: './first.component.html',
    styleUrls: ['./first.component.scss'],
    providers: [SoruService]
})
export class FirstComponent implements OnInit {
    public soruLst : [SoruModel];

    constructor( private soruServis : SoruService ) { }

    ngOnInit(){
        this.soruServis.getirSoruLst().subscribe( veri => {
            this.soruLst = veri as [SoruModel];
        })
    }

    //// MAKE SOME CHANGES ON "soruLst" locally 

    // Send updated 'soruLst' to service 
    updateSoruLst(){
        this.soruServis.updateSoruLst(this.soruLst);
    }

}

My Service :

import { Injectable } from '@angular/core';
import { SoruModel, SecenekModel } from './soruModel';
import { Http } from '@angular/http';

const metaJson = 'assets/data/Meta.json';

@Injectable()
export class SoruService {

    public sorular = [] as [SoruModel];

    constructor( private http:Http ) {
        this.sorular = [] as [SoruModel];
    }

    getirSoruLst() {
        return this.http.get(metaJson)
        .map(yanit => yanit.json())
    }

    updateSoruLst( soruLst : [SoruModel] ) {
             this.sorular = soruLst;
     }

    getSorular() : [SoruModel] {
        return this.sorular;
    }

}

Second Component :

mport { SoruService } from '../soru.service';
import { SoruModel, SecenekModel } from '../soruModel';

@Component({
    selector: 'app-second',
    templateUrl: './second.component.html',
    styleUrls: ['./second.component.scss'],
    providers: [SoruService]
})
export class SecondComponent implements OnInit {
    public soruLst : [SoruModel];

    constructor( private soruServis : SoruService ) { }

    ngOnInit(){
        this.soruLst = this.soruServis.getSorular();
        console.log(this.soruLst);
    }
}

This is what i want to do :

  1. in FirstComponent, get 'soruLst' from service and change it locally (Success)

  2. in FirstComponent, send changed 'soruLst' to service (Success - updateSoruLst )

  3. in Service, update 'sorular', in 'updateSoruLst' (Fail - it's not changing, only changing in function scope but i still can't read updated value) . I have problem with that :

    updateSoruLst( soruLst : [SoruModel] ) { this.sorular = soruLst; }

"this.sorular" value doesn't change globally.

  1. in SecondComponent, read updated 'sorular' from service ( Fail, still can't read updated value)

I think i must change my service , but could't find where must i change..

How can i update my object in service ?

like image 441
mevaka Avatar asked Mar 31 '18 21:03

mevaka


People also ask

How do I run JavaScript code when a value changes in AngularJS?

AngularJS binding, with ng-model and the double curly bracket syntax, does not allow you to run JavaScript code when a value changes. Thankfully, it does provide a $scope function, $watch (), for this purpose. Let's set up a simple watch to show how we can run additional code when values change. The $watch () is a function on the $scope service.

Why can't I use $apply() to update bindings in AngularJS services?

If you're building a larger application, there is a good chance that your remote service code will be encapsulated out of a controller and into an AngularJS Service. AngularJS Services do not have access to a $scope service because they do not have a view. As such, you cannot directly use $apply () to update bindings.

How to use $apply() and $digest() methods in angular?

The simplest solution to this is to use Angular's $apply() method on the $scope. The $apply() method accepts a single argument, which is a function. The function executes, then the $digest() functionality will be executed for the variables that changed.

Which version of angular is this post compatible with?

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12 In the Angular app, we need to make changes in local variables which are getting used and defined as global.


1 Answers

As JB Nizet mentioned, you should provide your service in a higher level than the FirstComponent and the SecondComponent. That means SoruService should be provided

  • either in your module class
  • or in the parent component class of the above components if there are any

In that way both the components will share the same instance of the service and you will be able achieve what you need.

Assuming that you have your components in the root module of the app.
Remove the provider attributes from the component decorators and change your module like below.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FirstComponent } from './first.component';
import { SecondComponent} from './second.component';
import { SoruService } from '../soru.service';

@NgModule({
   imports: [
      BrowserModule
   ],
   declarations: [
       AppComponent,
       FirstComponent,
       SecondComponent
   ],
   providers: [
       SoruService
   ],
   bootstrap: [AppComponent]
})
export class AppModule {
}

Also you can find a simple rxjs Subject example to share data among components using services in here.

like image 181
Senal Avatar answered Oct 02 '22 22:10

Senal