What's the use of an application that does not talk with a remote datastore to persist or retreive information. This is one that I was looking forward to when I started Angular2. I believe it's the same with you. We are not going to make a deep dive, but rather touch enough piece to help you move along. We will need a remote service that can persist contact information and give us back the contact list. For this exercise, I have created a sample NodeJS service that'll do the job - https://javascriptkrishnan.blogspot.com/2016/05/nodejs-mongodb-communication.html. Code is not pristine, but certainly get's us going. This NodeJS solution persists contact data passed to it in MongoDB and get's it back to us when requested. If you try this solution, please make sure you install and have accessible MongoDB. It's not just enough you have MongoDB, you need to fix it's access. Ensure right credentials are passed. How do you store user name and password for MongoDB in your Node JS solution. There are so many patterns. However, a simpler solution can be found here - https://javascriptkrishnan.blogspot.com/2016/06/application-initialization-dev-vs.html
Alrighty, what do we change in our code to be access this http service? Fairly simple. Remember we implemented mock services, it comes handy. All that we need to do is fix the services file to import http module and get data from remote location, instead of mock service. Here's the updated code. You may want to brush your knowledge on Promises
ContactsService.ts
Alrighty, what do we change in our code to be access this http service? Fairly simple. Remember we implemented mock services, it comes handy. All that we need to do is fix the services file to import http module and get data from remote location, instead of mock service. Here's the updated code. You may want to brush your knowledge on Promises
ContactsService.ts
/**
* Created by krishnansriramrama on 5/28/16.
*/
import {Injectable} from "angular2/core";
import {Http, Headers} from "angular2/http";
import 'rxjs/Rx';
import {Contact} from "./Contact";
@Injectable()
export class ContactsService {
ENPOINT_URL:string = "http://localhost:3000/contacts";
constructor(private _http: Http){}
getAllContacts() {
return this._http.get(this.ENPOINT_URL).map(res => res.json());
}
saveContact(contact: Contact) {
var contactBody: string = contact.toString();
var header = new Headers();
header.append('Content-Type', 'application/json');
console.log("Saving contact: " + contactBody);
return this._http.post(this.ENPOINT_URL, contactBody, {headers: header}).map(res => res.json());
}
}
No comments:
Post a Comment