Angular 2 y sus servicios de mierda

  • 1 Respuestas
  • 390 Vistas
Angular 2 y sus servicios de mierda
« en: Abril 26, 2017, 00:05:28 am »
Pues nada, he tenido que acabar en stackoverflow
os dejo el vinculo: https://stackoverflow.com/questions/43593420/angular-2-share-service-between-components-in-different-routes

y la pregunta original en ingles:


I have a behaviour in Angular 2 project that i don't know how to solve. I'm using webpack with Angular 2 2.3 (if this helps).

I have a complex project with structure like this:

    - index.ts
    - app.module.ts
    - app.component.ts
    - app.routes.ts
    - services
         - login.service.ts
    - +innerapp
         - inner.routes.ts
         - inner.module.ts
         - inner.component.ts
         - inner.component.html
         - services
             -inner.service.ts
         - insideinner
             - insideinner.component.ts
             - insideinner.component.html
             - header
                 - header.component.ts
                 - header.component.html
             - form
                 - form.component.ts
                 - form.component.html
   
When you execute shows login and then route to +innerapp. Inner.component.ts loads inner.services.ts and do a http call for data. A lot of data is moved from server and a let of BehaivorSubjects are initialized inside inner.service.ts.

All works fine, but in a moment user clicks button and loads form.component.ts with a big form. User fills form and click submit, in this moment inner.service is called to add data form. My surprise is inner.service haven't data, it's just initialised.

Code below.

Código: Javascript
  1.     //inner.routes.ts
  2.     export const routes = [
  3.       { path: '', children: [
  4.       { path: '', component: InnerComponent },
  5.       { path: 'form', component: FormComponent },
  6.       ]},
  7.     ];

inner.module.ts

   
Código: Javascript
  1.  import { routes } from './inner.routes';
  2.     import { InnerComponent } from './inner.component';
  3.     import { FormComponent } from './insideinner/form/form.component';
  4.  
  5.     // Services
  6.     import { InnerService } from './service/inner.service';
  7.  
  8.     @NgModule({
  9.       declarations: [
  10.         // Components / Directives/ Pipes
  11.         InnerComponent,
  12.         FormComponent
  13.       ],
  14.       imports: [
  15.         RouterModule.forChild(routes),
  16.       ],
  17.       providers: [
  18.         InnerService
  19.       ]
  20.     })
  21.     export class InnerModule {
  22.       public static routes = routes;
  23.     }

inner.component.ts:
Código: Javascript
  1.     @Component({
  2.       selector: 'inner',
  3.       templateUrl: './inner.component.html'
  4.     })
  5.     export class InnerComponent implements OnInit {
  6.  
  7.       constructor ( private innerService: innerService ) {
  8.  
  9.         this.innerService.fetchData()
  10.           .subscribe(
  11.             (response) => {
  12.               this.innerService.addData(response.json());
  13.             },
  14.         (error) => {
  15.           alert(error);
  16.         }
  17.       );
  18.    
  19.     }
  20.  
services/inner.services.ts
Código: Javascript
  1.     import { Injectable } from '@angular/core';
  2.     import { Observable, BehaviorSubject } from 'rxjs';
  3.     import { Headers, RequestOptions, Http, Response } from '@angular/http';
  4.    
  5.     @Injectable()
  6.     export class InnerService {
  7.    
  8.       // Observable string streams
  9.       public readonly data: Observable<string>;
  10.    
  11.       // Observable string sources
  12.       private _data: BehaviorSubject<string> = new BehaviorSubject(null);
  13.    
  14.       // private properties
  15.       private options: RequestOptions;
  16.    
  17.       constructor( public http: Http ) {
  18.         this.data = this._user.asObservable();
  19.    
  20.         // http standard values
  21.         let token = localStorage.getItem('token');
  22.         let cabs = new Headers({ Authorization: 'Bearer ' + token });
  23.         this.options = new RequestOptions({ headers: cabs });
  24.       }
  25.    
  26.       // Service message commands
  27.       public addData (t: string) {
  28.         this._data.next(t);
  29.       }
  30.    
  31.       public saveData(t: string) {
  32.    
  33.         return this.http.post(blabla,
  34.           {
  35.             data: t
  36.           },
  37.           this.options
  38.         ).map((res: Response) => {
  39.           this.addData(t);
  40.           return true;
  41.         }).catch(this.handleError);
  42.    
  43.       }
  44.    
  45.       private handleError (error: any) {
  46.         //code
  47.       }
  48.    
  49.       public fetchData(): Observable<any> {
  50.         return this.http.get(blabla, this.options)
  51.           .map((res) => { return res.body })
  52.           .catch(this.handleError);
  53.       }
  54.     }

insideinner/form/form.component.ts

Código: Javascript
  1.     import { Component, OnInit, ViewEncapsulation } from '@angular/core';
  2.    
  3.     // services & others
  4.     import { InnerService } from '../../services/inner.service';
  5.    
  6.     @Component({
  7.       selector: 'add-members',
  8.       templateUrl: './form.component.html',
  9.       encapsulation: ViewEncapsulation.None
  10.     })
  11.     export class FormComponent implements OnInit  {
  12.    
  13.       constructor(
  14.         private fb: FormBuilder,
  15.         private innerService: InnerService
  16.       ) {}
  17.    
  18.       public ngOnInit() {
  19.         this.showForm = false;
  20.       }
  21.    
  22.       public onSubmit(value: string) {
  23.    
  24.         this.innerService.saveData(value); //Fail here, inner service are without data
  25.       }
  26.    
  27.       public showAdd() {
  28.         this.showForm = true;
  29.       }
  30.     }

I read a lot of docs and read here similar problems, but solutions aren't working for me.

Valarjar
Hijo de Odyn

Re:Angular 2 y sus servicios de mierda
« Respuesta #1 en: Abril 26, 2017, 12:20:23 pm »
Pff la verdad es que yo angular, nunca lo he tocado, no se que decirte , a ver en stackoveflow