Passionate Coder
Passionate Coder

Reputation: 7294

Is there any difference in below syntax?

I am new in Angular.

#1 : I am making http call in angular and came across Observable and found below 2 syntax which is giving same result when call through a component

as you can see in first I have defined type as Observable and imported Observable from rxjs and in 2nd this is working without any type declaration or import

#2 I need to know both are same differnce is in only syntax? OR both are different?

Service.ts

import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http"
import { Observable } from 'rxjs';
@Injectable({
    providedIn : "root"
})

export class ObservableService{
    constructor(private http : HttpClient){}

    getEmployeeDetail(id) : Observable<any>{            
        return this.http.get("http://dummy.restapiexample.com/api/v1/employee/"+id);        
    }
}

Service.ts

import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http"
@Injectable({
    providedIn : "root"
})

export class ObservableService{
    constructor(private http : HttpClient){}

    getEmployeeDetail(id){            
        return this.http.get("http://dummy.restapiexample.com/api/v1/employee/"+id);        
    }
}

Upvotes: 0

Views: 34

Answers (1)

dmcgrandle
dmcgrandle

Reputation: 6070

They will function exactly the same, and in fact both will return an Observable, but in the first case you are explicitly declaring the return type of the method, and in the second you are not.

This is actually due to typescript, not angular. Check the docs here

The reason typescript doesn't complain when you don't declare the return type explicitly is because of type inference. There is a fairly good explanation of this here, reproduced below:

Function Return Types

The return type is inferred by the return statements e.g. the following function is inferred to return a number.

function add(a: number, b: number) { return a + b; }

This is an example of types flowing bottom out.

Upvotes: 1

Related Questions