Code Ratchet
Code Ratchet

Reputation: 6029

'Promise' is not assignable to type 'Model' - Angular2 / Firebase

I have the following method inside my service which returns a single record from Firebase that matches the bugId passed in:

// Note this is located within bugservice.ts

   getBug(bugId: string): Promise<Bug> {

    return this.bugsDbRef
        .child(bugId)
        .once('value')
        .then(snapshot => {
            const bugInfo = snapshot.val() as Bug;
            bugInfo.id = snapshot.key;
        }) as Promise<Bug>;
}

Inside my bugDetail component I inject the above service into my bugDetail component and then call the above method as shown here:

export class BugDetailComponent implements OnInit, OnDestroy {

private subscription: Subscription;

private bugDetail: Bug = new Bug(null,null,null,null,null,null,null,null,null); // Trying to populate from Service Call i.e getBug    
private bugId: string; // Come from URL

constructor(private bugService: BugService, private activatedRoute: ActivatedRoute) { }

ngOnInit() {
    this.configureForm();

    this.subscription = this.activatedRoute.params.subscribe(
        (param: any) => {
            this.bugId = param['id'];
        });

    const t = this.bugService.getBug(this.bugId);

    console.log(t);

}
}

However when I console.log t the following is displayed in the console:

enter image description here

When I remove t and replace it with

this.bugDetail = this.bugService.getBug(this.bugId);

The error message I get is:

Type 'Promise' is not assignable to type 'Bug'. Property 'id' is missing in type 'Promise'.

Can someone please explain to me how I can access the bug details retrieved from the service inside the BugDetail Component?

Upvotes: 0

Views: 301

Answers (1)

cartant
cartant

Reputation: 58400

getBug returns a Promise<Bug> - which is a promise that will resolve to a Bug value. Promises resolve asynchronously and the resolved value is made available to the function passed to the promise's then method. That's the only way you can access the resolved value.

You could assign to this.bugDetail, like this:

this.bugService
    .getBug(this.bugId)
    .then(bug => { this.bugDetail = bug; });

You might want to read JavaScript Promises: an Introduction.

Upvotes: 1

Related Questions