prevox
prevox

Reputation: 576

Subscribe() returns undefined

I'm not being able to use the result from subscribe() outside of subscribe(), console.log always returns undefined. My assumption is that it has something to do with the async thing but I don't know a workaround to make this work. Should I use promise instead?

export class MyComponent implements OnInit {
    textt: String;

    constructor(private tstService: MyComponentService) { this.source = new LocalDataSource(this.data) }

    ngOnInit(): void {
        this.tstService.getTstWithObservable()
        .map(result => result.map(i => i.user.data))
        .subscribe(
           res => { this.textt = res[0].title; }
       );
    }

    data = [
        {
          title: this.textt,
          sdate: '01/04/1990',
          edate: '30/09/1990',
        },
      ];

    source: LocalDataSource;
}

Upvotes: 1

Views: 4948

Answers (1)

Batajus
Batajus

Reputation: 6257

You're right, the problem is that the subscribe works asynchronous. The data.title isn't set at the creation, because this.textt is not set at the time the component is created and it will be set at another (not known) time.

To update your data attribute. You can create it inside the subscription or you simply set the title inside it.

ngOnInit(): void {
    this.tstService.getTstWithObservable()
    .map(result => result.map(i => i.user.data))
    .subscribe(
       res => { 
           this.textt = res[0].title; 
           this.data.title = this.textt;
       }
   );
}

Upvotes: 2

Related Questions