1

I'm a noob in this Typescript world and Angular2, so maybe the question can cause funny reactions.

In my app I need to retrieve data from a WS REST, the data comes in Json format.

data:                     Object
  outCurpacatens:         [1]
      0:                  Object
            agenda:       877
            codestado:    1
            correlativo:  1
            estado:       "RESERVADO"
            idreserva:    18142568
            idservicio:   2
            idsucursal:   2
            materno:      "MAT6398674"
            nombre:       "FELIPE ALEJANDRO"
            obs:          null
  mensaje:                null

And my Interface looks like:

export interface Agenda {
   agenda: number;
   codestado: number;
   correlativo: number;
   estado: String;
   idreserva: number;
   idservicio: number;
   idsucursal: number;
   materno: String;
   nombre: String;
   obs: String;
}

agenda.components.ts

export class AgendaComponent implements OnInit {

 public localState: any;
 public es: any;
 public res: any;
 public jsonData: any;

 constructor(public route: ActivatedRoute, private auth: Auth, private agendService: AgendaService) {
 }   

  public ngOnInit() {
 }

 testPatch(){
   this.res = this.agendService.getAgendaByDate('12')
              .subscribe(data => {
                                    this.jsonData = data;
                                  }
      );
 }

}

agendaService.ts

@Injectable()
export class AgendaService {

    private baseUrl = 'https://myweb';
    private serviceUrl = '/agenda/getmethod';
    private headers: Headers;

    constructor(private http:Http, private authService: Auth){
    }

    private getOptions(): RequestOptions {
        let headers: Headers = new Headers();
        let token = localStorage.getItem('id_token');
        headers.append('content-type', 'application/json; charset=utf-8');
        headers.append('Authorization', 'Bearer '+ token);
        let opts = new RequestOptions({headers: headers});
        opts.headers = headers;
        return opts;
    }

    getAgendaByDate(fecha:string): Observable<Agenda> {
         /** input parameters setted with cons until resolve issue **/
         return this.http.get(`${this.baseUrl}${this.serviceUrl}?id=877&fecha=23082017`)
        .map((res: Response) => {
                                    res.json();
                                }, this.getOptions());
    }

}

In the compilation I get this Error:

agenda/agenda.component.ts (52,59): Property 'outCurpacatens' does not exist on type 'Agenda'.

I know there's something I'm missing, but I don't know what.

EDIT UPDATE:

Now I have put this:

agendaService.ts

 getAgendaByDate() {
    return this.http.get(`${this.baseUrl}${this.serviceUrl}?id=877&fecha=23082017`)
    .map((res: Response) => {return res.json().data.outCurpacatens[0]}).catch(this.handleError);
}


handleError(error) {
    console.error(error);
    console.log("Error: "+error);
    return Observable.throw(error.json().error || 'Server error');
}

And I'm getting this, in the console:

Console

Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }  main.bundle.js:161:9
Error: Response with status: 0  for URL: null 

Regards.

Community
  • 1
  • 1
MBrownG
  • 53
  • 1
  • 8
  • 2
    Well it doesn't :) I think based on what I am seeing, you want to extract the data from `outCurpacatens`´like `.map(res => res.json().data.outCurpacatens[0])` – AT82 Apr 24 '17 at 18:10
  • The error references an error in the component, can you provide that code so we can see it? – rayepps Apr 24 '17 at 18:45
  • @raykrow I added agendaService and agenda.component. – MBrownG Apr 24 '17 at 19:06
  • @MBrownG What's this `getOptions()` why are you calling it where you are, meaning after http-request? – AT82 Apr 24 '17 at 19:16
  • @AJT_82 doesn't matter too much, if you remove getOptions nothing change. Still can't retrieve the data from the json to my front end (even if I put {{ jsonData }} on it, I'm not so noob xD ). – MBrownG Apr 24 '17 at 20:13

1 Answers1

1

You are missing a return in your mapping, it should look like this:

.map((res: Response) => { return res.json() }

Once this is done, you maybe want to extract the object inside the array that corresponds Agenda in your response. That would mean the first (and only) object in the array outCurpacatens, so how to get a hold of that object would be:

.map((res: Response) => { return res.json().data.outCurpacatens[0]})

Also, since you have an interface, make use of it and declare the variable as the type. I assume that would be jsonData, so instead declare it:

jsonData: Agenda = <Agenda>{};

Once this is done, you would probably need to use the safe navigation operator to safeguard null values, like:

{{jsonData?.myProperty}}

or wrap your template in an *ngIf="jsonData"

hope this helps! :)

Update: Make sure you are calling testPatch from somewhere. Here's a

Demo

where testPatch is called in ngOnInit. The code should work if you are receiving your data properly.

AT82
  • 71,416
  • 24
  • 140
  • 167
  • Have you made sure that you are receiving the data properly? I guess you have checked the network tab, but just make sure, so that we can at least eliminate that issue :) – AT82 Apr 25 '17 at 13:25
  • Updated answer, please compare your code with the one in the plunker. If you still don't get the code to work, could you please try and reproduce the issue in a Plunker and I'd be happy to take a look :) – AT82 Apr 25 '17 at 13:41
  • Thanks @AJT_82 your Demo works fine, but I'm still getting an Error. I have updated the question with it. Maybe is the server side? – MBrownG Apr 26 '17 at 12:09
  • Yes, seems like it could be server side. Have you checked that you are receiving data in the browser developer tools (network tab)? – AT82 Apr 26 '17 at 12:19
  • Yeap, without a problem. Status Code: Green light 200 OK(I'm using Firefox). In the response tab, everything looks fine. Time 1ms. – MBrownG Apr 26 '17 at 13:03
  • Have you checked these, mentions cors issue: http://stackoverflow.com/questions/39520209/angular-2-exception-response-with-status-0-for-url-null and http://stackoverflow.com/questions/38286250/exception-response-with-status-0-for-url-null-in-angular2 – AT82 Apr 26 '17 at 13:09
  • finally it seems to be a CORS problem. I installed the CORS extension in chrome and work well. – MBrownG May 03 '17 at 12:07
  • Yes and you needed to make the changes like in the answer right? :) Well, good that you got your CORS issue solved :) – AT82 May 03 '17 at 12:11
  • It helps a lot to discover the problem, so maybe I have to mark your answer as correct and thanks a lot. – MBrownG May 03 '17 at 12:47