I am facing an issue with Angular 2 (apologies for my limited English proficiency...).
I need to be able to modify a component variable from another component. The trouble is, this component variable remains undefined outside the subscribe function even though it is clearly defined within. Therefore, I am unable to access this variable without being within this specific component.
Below is my service named MailRepertoryService:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MailRepertoryService {
constructor(private http: Http) { }
getMailsRepertory() {
return this.http
.get('data/dossiers.json')
.map(res => res.json());
}
getMailsRepertoryFields() {
return this.http
.get('data/champs.json')
.map(res => res.json())
}
}
And here is my AppComponent:
import { Component, Input } from '@angular/core';
import { MailRepertoryService } from './services/mail.repertory.service';
import { Box, Field, Mail } from './types/mailbox.type';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private title = 'Em Ta Box';
boxRepertory: Box[];
mailRepertory: Box;
fields: Field[];
private errors: string;
constructor(private mailRepertoryService: MailRepertoryService) {}
ngOnInit() {
this.mailRepertoryService.getMailsRepertory().subscribe(
(mailRepertories: Box[]) => {
this.boxRepertory = mailRepertories;
console.log(this.boxRepertory); // object displayed correctly
},
error => {
console.error(error);
this.errors = error;
}
);
this.mailRepertoryService.getMailsRepertoryFields().subscribe(
data => this.fields = data,
error => {
console.error(error);
this.errors = error;
}
);
console.log(this.boxRepertory); // remains undefined
}
}
Is there a way for me to access the this.boxRepertory variable outside of the subscribe method?
Thank you in advance.