Beginning AngularJS

(WallPaper) #1

ChApter 1 ■ JAvASCrIpt You Need to KNow


The interesting part of this example is the success method. It takes a function as an argument. We didn’t bother
to store the function in a variable this time. It is created right there in the method call (a very common technique).
The $http.post() method has to call a server and wait for a response. At some later point, with all going well, the
success method will execute the callback function that we passed to it. This process takes, typically, at least a couple
of seconds or so. Have a look at how the output for such a scenario would look.


1
3
2


The key thing to observe here is that 3 comes before 2 in the output. This is because the callback function, which
contains the console.log('2') statement, takes place at some point in the future. Thanks to the power of callbacks,
your program doesn’t have to wait around; it continues executing as normal, happy in the knowledge that there will be
“call back” later.


JSON

JavaScript Object Notation, or JSON, is a lightweight data-interchange format. Essentially, it is way of representing
data in a way that is much more compact than XML yet still relatively human and totally machine-readable. If you
need to send data from place to place, or even store it somewhere, JSON is often a good choice.
Because JSON is JavaScript (well, a subset of JavaScript, to be precise), it is easy to work with. Unlike XML, it is
considerably faster over the wire. I won’t labor too much on JSON, but I will show you what it looks like. Listing 1-33
shows a sample of JSON data.


Listing 1-33. Sample JSON Data


{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}


I covered JavaScript objects earlier, so I hope this will look familiar. This is essentially a JavaScript object with a
bunch of properties representing contact data for a John Smith. firstName and lastName have simple string values.
The address property is itself represented as an object, and the phoneNumbers property is an array.

Free download pdf