DEV Community

Discussion on: Angular Component Subscription vs. AsyncPipe: Use Pipes When Possible

Collapse
 
mnx_vsh profile image
Manish

Thanks for explain this, I have my doubts: As I am starting to learn angular I got confused .

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'my-app',
template: `

{{a.title}}


`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
public name = 'Angular';
public dataValues:object;

public configUrl = 'jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }

showConfig() {
return this.http.get(this.configUrl)
.subscribe(data => this.dataValues = data);
}
}

Is that line return this.http.get(this.configUrl) return observable , If yes then why din't we import observable from rxjs.

Why do we import Observable with simple code like :

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Config {
title: string;
body: string;
}

@Component({
selector: 'my-app',
template: `

{{a.title}}


`,
styleUrls: ['./app.component.css']
})

export class AppComponent {
public name = 'Angular';
public dataValues: object;
public config: Config;

public configUrl = 'jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }

showConfig() {
return this.http.get(this.configUrl)
.subscribe((data: Config) => this.dataValues = data);
}

}

Collapse
 
eyassh profile image
Eyas

Is that line return this.http.get(this.configUrl) return observable , If yes then why din't we import observable from rxjs.

Yes, the this.http.get(...) line returns an Observable. In general my code snippets don't include the imports.

In general you can import specific types you depend on but that isn't actually strictly necessary. The implementation of HttpClient.get imports Observable and returns it, so all you need to do is include the implementation of HttpClient, which you do.

In general ES6 imports are for things you directly depend on. Those imports will transitively import any things they depend on.