I have an issue about Angular 2 (sorry about my english that is not good enough...).
I would like to manipulate a component variable from an other component. The problem is this component variable is undefined outside the subscribe function whereas it is clearly viewable inside. So, I can't expect to access this variable without this component.
Here is my service 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); // visible object
},
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); // undefined
}
}
How can I access to this.boxRepertory variable outside the subscribe ?
With Thanks.