Это мой component.ts
export class OrganizationsComponent {
public organizations;
constructor(public access: OrganizationService) {
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.info(this.organizations);
}))
console.info(this.organizations)
}
Как получить данные вне конструктора?
Что вы получаете в консоли?





Прежде всего, вы не можете получить доступ к свойству organizations за пределами блока подписки из-за асинхронных свойств JavaScript/TypeScript. Вы можете прочитать больше о цикле событий в здесь, так как он дает более подробное объяснение. Поэтому вам нужно будет использовать .subscribe(), чтобы вернуть наблюдаемое значение.
Проблема с
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
}));
console.info(this.organizations);
заключается в том, что console.info(this.organizations); завершит выполнение до завершения подписки, поэтому будет напечатано значение undefined. Вместо этого правильный способ печати organizations заключается в следующем:
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.info(this.organizations);
}));
Кроме того, как объясняется в комментариях, вы не должны возвращать наблюдаемое в конструкторе. Вместо этого я рекомендую вам вернуть его в жизненном цикле OnInit.
ngOnInit(): void {
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.info(this.organizations);
}));
}
В качестве альтернативы вы можете вместо этого сохранить его как наблюдаемый объект и вернуть его позже, когда он вам действительно понадобится.
organizations: Observable<any>;
ngOnInit() {
this.organizations = this.access.getOrganizations();
}
someOthermethod() {
this.organizations.subscribe(res => {
console.info(res);
});
}
First of all, you should not call the service inside the constructor
Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn't do anything. It certainly shouldn't call a function that makes HTTP requests to a remote server as a real data service would.
Вы должны изменить свой OrganisationsComponent на что-то вроде ниже: ~
export class OrganisationsComponent {
dataFromServer: Observable<any>;
constructor(private access: OrganizationService) {}
ngOnInit() {
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.info(this.organizations);
}));
// console.info(this.organizations); // undefined because by the time subscribe is called you are console logging it
setTimeout(() => { console.info(this.organizations); },5000);
}
}
Explanation:~
You will not get the data outside the subscribe block because it'sasync, you don't have value there!
or
precisely undefined -> 'getOrganizations()' hadn't returned Observableby the time it's logging to console.
So, based on your service call response time you can test insetTimeout.
Простой пример с вашей проблемой здесь СТЭКБЛИЦ
Надеюсь это поможет !
Просто, вы можете сделать так
constructor(public access: OrganizationService) {}
get(){
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.info(this.organizations);
}))
console.info(this.organizations)
}
ngOninit(){
this.get();
}
Вы можете преобразовать наблюдаемое в обещание и дождаться его, поэтому, когда обещание будет разрешено, значение будет доступно.
export class OrganizationsComponent {
public organizations;
constructor(public access: OrganizationService) {}
async ngOnInit() {
this.organizations = await this.access.getOrganizations()
.pipe(first())
.toPromise();
console.info("Organization Name: ", this.organizations[0].name)
}
}
Пожалуйста, добавьте больше описания в свой вопрос.