Getting Data From Server using http GET Method
We use it to make ajax calls to the server.
The Http class provides the get() method for getting a resource, post() for creating it, put() for updating it, delete() for deleting resource and head() for getting metadata regarding a resource.
Observables
- Observables is a new primitive type which acts as a blueprint for how we want to create streams, subscribe to them, react to new values, and combine streams together to build new ones.
- RxJS stands for *R*eactive E*x*tensions for *J*ava*S*cript, and its a library that gives us an implementation of Observables for JavaScript.
Subscribe()
By calling subscribe onto an observable it:
- 1. Turns the observable hot so it starts producing.
- 2. Lets us pass in a callback function so we react when anything is pushed onto the final stream in the observable chain.
Example:
Step1: Create a Service., It will create myservice.
ng g service myservice
import { Injectable } from '@angular/core';
import { Http, HttpModule } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MyserviceService {
constructor(private _http: Http) { }
getdata()
{
return this._http.get('https://ganesha-51b6f.firebaseio.com/fname.json')
}
}
Step 2 : Create App.Component.ts(In the following code if JSON error is occurred then remove .json() from datas.json() )
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { MyserviceService } from 'app/myservice.service';
import { Http , HttpModule } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [MyserviceService]
})
export class AppComponent implements OnInit {
title = 'app works!';
constructor(private service: MyserviceService){}
ngOnInit()
{
this.service.getdata().subscribe(
datas => console.log(datas.json())
);
}
}
Hello,
Thanks for great tutorial. I installed your code and everything is working fine but getting this error
core.js:3123 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
localhost/:1 Failed to load mbhf.aronasoft.com/app/blogs_api.php: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4200’ is therefore not allowed access.
core.js:1673 ERROR Response
defaultErrorLogger @ core.js:1673
Thanks
Sudhir