{"_id":"56d1f33b00a2a70b00b365d4","parentDoc":null,"version":{"_id":"56d1f33700a2a70b00b3658e","project":"5526c95cf69851170038b48f","__v":2,"createdAt":"2016-02-27T19:04:23.946Z","releaseDate":"2016-02-27T19:04:23.946Z","categories":["56d1f33900a2a70b00b3658f","56d1f33900a2a70b00b36590","56d1f33900a2a70b00b36591","56d1f33900a2a70b00b36592","56d1f33900a2a70b00b36593","56d1f33900a2a70b00b36594","56d1f33900a2a70b00b36595","56d1f33900a2a70b00b36596","56d1f33900a2a70b00b36597","56d1f33900a2a70b00b36598","56d1f33900a2a70b00b36599","56d1f33900a2a70b00b3659a","571f9497ada30c34003b7cee"],"is_deprecated":false,"is_hidden":false,"is_beta":true,"is_stable":true,"codename":"beta","version_clean":"2.0.0-beta","version":"2.0.0-beta"},"__v":13,"category":{"_id":"56d1f33900a2a70b00b36592","project":"5526c95cf69851170038b48f","version":"56d1f33700a2a70b00b3658e","pages":["56d1f33b00a2a70b00b365d3","56d1f33b00a2a70b00b365d4","56d1f33b00a2a70b00b365d5","56d1f33b00a2a70b00b365d6","56d1f33b00a2a70b00b365d7","56d1f33b00a2a70b00b365d8","56d1f33b00a2a70b00b365d9","56d1f33b00a2a70b00b365da","56d1f33b00a2a70b00b365db","56d1f33b00a2a70b00b365dc","56d5984cf612b80b00fb6997"],"__v":2,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-04-10T15:43:12.697Z","from_sync":false,"order":2,"slug":"ionic-user","title":"Ionic User"},"project":"5526c95cf69851170038b48f","user":"5526ca4cf69851170038b496","updates":["560c29cde6112f2300b8d9c9","560c2d6ad1084b2300c6df4b","5685a70b009a8d0d00797139","56f866c9f6081e0e003d1e03"],"next":{"pages":[],"description":""},"createdAt":"2015-09-22T14:10:15.868Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":4,"body":"Ionic User helps you keep track of all the users of your app, which we use for a variety of services such as Push Notifications.\n\nEven if you have user tracking in your application, many Ionic services can be greatly enhanced with user data. \n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Getting a User\"\n}\n[/block]\nAssuming you've followed the [Getting Started](doc:io-install) guide, you're already 99% of the way there!  Just add the following code to your app to get a `current user`.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// this will give you a fresh user or the previously saved 'current user'\\nvar user = Ionic.User.current();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nWe recommend doing this each time your app starts or whenever a user logs in. You can send whatever user data you like to the user service, such as their name, email, total purchase amount, favorite kind of ice cream, or their favorite novel.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"User Login\"\n}\n[/block]\nThis is better explained using the [User Overview](doc:user-overview) and [User Authentication](doc:user-authentication) pages.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"User Logout\"\n}\n[/block]\nTo logout an authenticated user, use the Ionic.Auth.logout method\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"Ionic.Auth.logout();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Determining if a user is logged in\"\n}\n[/block]\nYou can find out if the current user is logged in by checking if they have been authenticated:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var user = Ionic.User.current();\\n\\nif (user.isAuthenticated()) {\\n  // user is logged in\\n} else {\\n  // user is NOT logged in\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Resetting a user's password\"\n}\n[/block]\nResetting a user's password immediately changes their password to a generated password. The new password is then sent to them in an email which they can then use to login. We recommend informing the user to change their password after resetting it.\n\nTo reset a user's password, call the `resetPassword` method, which returns a promise:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var success = function(response) {\\n\\tconsole.log('password reset!');\\n};\\n\\nvar failure = function(error) {\\n  console.error('password NOT reset');\\n};\\n\\nuser.resetPassword().then(success, failure);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Working with user data\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Important!\",\n  \"body\": \"Changes to a user are not persisted unless you call `save()` on the user object. It's a good idea to call save() after each batch of changes. See the section on saving users below.\"\n}\n[/block]\n## User Details\n\nSome common user data, such as `name`, `image`, and `password` are stored separately from custom data. We call them user details, and they can be accessed and changed by using the `user.details` object.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"user.details.name = \\\"Rick Deckard\\\";\\nuser.details.image = \\\"http://i.imgur.com/TfWWm3T.jpg\\\";\\nuser.details.password = \\\"secret\\\";\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n## Custom Data\n\nAssuming you've assigned the current user to the `user` variable, you can set custom data for that user like so:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// You can store JavaScript strings, numbers, booleans, arrays, and json objects.\\n\\n// strings\\nuser.set('address', '1600 Pennsylvania Avenue');\\n\\n// numbers\\nuser.set('points', 25);\\n\\n// arrays\\nuser.set('hobbies', ['reading', 'writing']);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nYou can later get that data using `get`:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var address = user.get('address');\\nvar points = user.get('points');\\nvar hobbies = user.get('hobbies');\\n\\n// you can also assign defaults if the user does not have the property\\nvar points = user.get('points', 5);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nIf you want to remove data from the user you can use `unset`:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"user.unset('address');\\nuser.unset('points');\\nuser.unset('hobbies');\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Angular JSON\",\n  \"body\": \"When storing complex objects from Angular, you may get the error `Invalid operator '$$hashkey'`. The User API does not allow fields prefixed with `$`, so you'll need to remove them using Angular's [`toJson` method](https://docs.angularjs.org/api/ng/function/angular.toJson), and then call `JSON.parse()` to turn it back into an object.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Data Types\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"JavaScript Types\",\n  \"body\": \"While we reference this feature as **Data Types**, it's important to know that these are not true JavaScript types. Read below to find out more.\"\n}\n[/block]\nWhile it's incredibly easy to work with basic data, more complex datasets might be too cumbersome to simply deal with as a straight JSON Object or Array. This is why we've introduced **Data Types**. \n\nData Types allow you to define a class that implements two methods (`toJSON` and `fromJSON`) which just give us a way to predictably serialize and deserialize your class so that it can be safely stored as one of the basic types we support for storage. You then register your class using `Ionic.DataType.register` with a unique name. \n\nTo introduce you to the basics we'll use one of the basic data types, `UniqueArray`, that we register automatically. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var user = Ionic.User.current();\\n\\n// let's set a array of friend ids\\n// notice how we've set id:5 twice and used the new keyword\\nvar uniqueIds = new Ionic.DataTypes.UniqueArray([5, 2, 5, 30]);\\n\\n// uniqueIds is a class, but we can still set it with user.set\\nuser.set('friends', uniqueIds);\\n\\n// because this is a class and not a basic array you won't have the basic array methods you normally expect\\nvar friends = user.get('friends');\\nfriends.length; // this will fail\\n\\n// you can access the basic array using the data property of the UniqueArray\\nfriends.data; // this will be [5, 2, 30]\\n\\n\\n// now let's add some values\\nfriends.push(3); // this will push 3 into the data\\nfriends.push(5); // this will do nothing because 5 is already set\\n\\n// now let's say we no longer want the friend id of 2\\nfriends.pull(2); // this will remove the 2 value from the array.\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nWhen you save the user, the `friends` data will be stored, and when you load the user back again, you will be able to work with the friends data just as you previously were. You get all the convenience of working with a class, but don't need to worry converting it back and forth each time you save and load!\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Saving users\"\n}\n[/block]\nEach user object has a `save` method. Saving persists the user data to the ionic platform so that it can be loaded later. \n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Local Storage\",\n  \"body\": \"If the user object matches the _current user_ we will store the user in the device's localStorage. You should be mindful of this if you have any app code that clears out localStorage.\\n\\nThe user is stored in localStorage that it can be immediately retrieved without loading data from the ionic platform. It is up to you to decide when and how often you should load data from the ionic platform using the `load` method of the user object.\"\n}\n[/block]\nThe save method returns a promise, which you can use to handle any errors during save:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// you can fire and forget if you don't care about handling errors.\\nuser.save();\\n\\n// otherwise you can handle the success and failure using the promise returned by save()\\n\\nvar success = function(response) {\\n  console.log('user was saved');\\n};\\n\\nvar failure = function(error) {\\n  console.log('user was NOT saved');\\n};\\n\\nuser.save().then(success, failure);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Loading users\"\n}\n[/block]\nIf you want to load a user as stored on the ionic platform, you can use the static `Ionic.User.load` method:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var success = function(loadedUser) {\\n\\t// if this user should be treated as the current user,\\n  // you will need to set it as such:\\n  Ionic.User.current(loadedUser);\\n  \\n  // assuming you previous had var user = Ionic.User.current()\\n  // you will need to update your variable reference\\n  user = Ionic.User.current();\\n};\\n\\nvar failure = function(error) {\\n  console.log('something went wrong');\\n};\\n\\nIonic.User.load('user-id').then(success, failure);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","excerpt":"Start tracking users in your Ionic app","slug":"user-usage","type":"basic","title":"Usage"}

Usage

Start tracking users in your Ionic app

Ionic User helps you keep track of all the users of your app, which we use for a variety of services such as Push Notifications. Even if you have user tracking in your application, many Ionic services can be greatly enhanced with user data. [block:api-header] { "type": "basic", "title": "Getting a User" } [/block] Assuming you've followed the [Getting Started](doc:io-install) guide, you're already 99% of the way there! Just add the following code to your app to get a `current user`. [block:code] { "codes": [ { "code": "// this will give you a fresh user or the previously saved 'current user'\nvar user = Ionic.User.current();", "language": "javascript" } ] } [/block] We recommend doing this each time your app starts or whenever a user logs in. You can send whatever user data you like to the user service, such as their name, email, total purchase amount, favorite kind of ice cream, or their favorite novel. [block:api-header] { "type": "basic", "title": "User Login" } [/block] This is better explained using the [User Overview](doc:user-overview) and [User Authentication](doc:user-authentication) pages. [block:api-header] { "type": "basic", "title": "User Logout" } [/block] To logout an authenticated user, use the Ionic.Auth.logout method [block:code] { "codes": [ { "code": "Ionic.Auth.logout();", "language": "javascript" } ] } [/block] [block:api-header] { "type": "basic", "title": "Determining if a user is logged in" } [/block] You can find out if the current user is logged in by checking if they have been authenticated: [block:code] { "codes": [ { "code": "var user = Ionic.User.current();\n\nif (user.isAuthenticated()) {\n // user is logged in\n} else {\n // user is NOT logged in\n}", "language": "javascript" } ] } [/block] [block:api-header] { "type": "basic", "title": "Resetting a user's password" } [/block] Resetting a user's password immediately changes their password to a generated password. The new password is then sent to them in an email which they can then use to login. We recommend informing the user to change their password after resetting it. To reset a user's password, call the `resetPassword` method, which returns a promise: [block:code] { "codes": [ { "code": "var success = function(response) {\n\tconsole.log('password reset!');\n};\n\nvar failure = function(error) {\n console.error('password NOT reset');\n};\n\nuser.resetPassword().then(success, failure);", "language": "javascript" } ] } [/block] [block:api-header] { "type": "basic", "title": "Working with user data" } [/block] [block:callout] { "type": "info", "title": "Important!", "body": "Changes to a user are not persisted unless you call `save()` on the user object. It's a good idea to call save() after each batch of changes. See the section on saving users below." } [/block] ## User Details Some common user data, such as `name`, `image`, and `password` are stored separately from custom data. We call them user details, and they can be accessed and changed by using the `user.details` object. [block:code] { "codes": [ { "code": "user.details.name = \"Rick Deckard\";\nuser.details.image = \"http://i.imgur.com/TfWWm3T.jpg\";\nuser.details.password = \"secret\";", "language": "javascript" } ] } [/block] ## Custom Data Assuming you've assigned the current user to the `user` variable, you can set custom data for that user like so: [block:code] { "codes": [ { "code": "// You can store JavaScript strings, numbers, booleans, arrays, and json objects.\n\n// strings\nuser.set('address', '1600 Pennsylvania Avenue');\n\n// numbers\nuser.set('points', 25);\n\n// arrays\nuser.set('hobbies', ['reading', 'writing']);", "language": "javascript" } ] } [/block] You can later get that data using `get`: [block:code] { "codes": [ { "code": "var address = user.get('address');\nvar points = user.get('points');\nvar hobbies = user.get('hobbies');\n\n// you can also assign defaults if the user does not have the property\nvar points = user.get('points', 5);", "language": "javascript" } ] } [/block] If you want to remove data from the user you can use `unset`: [block:code] { "codes": [ { "code": "user.unset('address');\nuser.unset('points');\nuser.unset('hobbies');", "language": "javascript" } ] } [/block] [block:callout] { "type": "danger", "title": "Angular JSON", "body": "When storing complex objects from Angular, you may get the error `Invalid operator '$$hashkey'`. The User API does not allow fields prefixed with `$`, so you'll need to remove them using Angular's [`toJson` method](https://docs.angularjs.org/api/ng/function/angular.toJson), and then call `JSON.parse()` to turn it back into an object." } [/block] [block:api-header] { "type": "basic", "title": "Data Types" } [/block] [block:callout] { "type": "danger", "title": "JavaScript Types", "body": "While we reference this feature as **Data Types**, it's important to know that these are not true JavaScript types. Read below to find out more." } [/block] While it's incredibly easy to work with basic data, more complex datasets might be too cumbersome to simply deal with as a straight JSON Object or Array. This is why we've introduced **Data Types**. Data Types allow you to define a class that implements two methods (`toJSON` and `fromJSON`) which just give us a way to predictably serialize and deserialize your class so that it can be safely stored as one of the basic types we support for storage. You then register your class using `Ionic.DataType.register` with a unique name. To introduce you to the basics we'll use one of the basic data types, `UniqueArray`, that we register automatically. [block:code] { "codes": [ { "code": "var user = Ionic.User.current();\n\n// let's set a array of friend ids\n// notice how we've set id:5 twice and used the new keyword\nvar uniqueIds = new Ionic.DataTypes.UniqueArray([5, 2, 5, 30]);\n\n// uniqueIds is a class, but we can still set it with user.set\nuser.set('friends', uniqueIds);\n\n// because this is a class and not a basic array you won't have the basic array methods you normally expect\nvar friends = user.get('friends');\nfriends.length; // this will fail\n\n// you can access the basic array using the data property of the UniqueArray\nfriends.data; // this will be [5, 2, 30]\n\n\n// now let's add some values\nfriends.push(3); // this will push 3 into the data\nfriends.push(5); // this will do nothing because 5 is already set\n\n// now let's say we no longer want the friend id of 2\nfriends.pull(2); // this will remove the 2 value from the array.\n", "language": "javascript" } ] } [/block] When you save the user, the `friends` data will be stored, and when you load the user back again, you will be able to work with the friends data just as you previously were. You get all the convenience of working with a class, but don't need to worry converting it back and forth each time you save and load! [block:api-header] { "type": "basic", "title": "Saving users" } [/block] Each user object has a `save` method. Saving persists the user data to the ionic platform so that it can be loaded later. [block:callout] { "type": "danger", "title": "Local Storage", "body": "If the user object matches the _current user_ we will store the user in the device's localStorage. You should be mindful of this if you have any app code that clears out localStorage.\n\nThe user is stored in localStorage that it can be immediately retrieved without loading data from the ionic platform. It is up to you to decide when and how often you should load data from the ionic platform using the `load` method of the user object." } [/block] The save method returns a promise, which you can use to handle any errors during save: [block:code] { "codes": [ { "code": "// you can fire and forget if you don't care about handling errors.\nuser.save();\n\n// otherwise you can handle the success and failure using the promise returned by save()\n\nvar success = function(response) {\n console.log('user was saved');\n};\n\nvar failure = function(error) {\n console.log('user was NOT saved');\n};\n\nuser.save().then(success, failure);", "language": "javascript" } ] } [/block] [block:api-header] { "type": "basic", "title": "Loading users" } [/block] If you want to load a user as stored on the ionic platform, you can use the static `Ionic.User.load` method: [block:code] { "codes": [ { "code": "var success = function(loadedUser) {\n\t// if this user should be treated as the current user,\n // you will need to set it as such:\n Ionic.User.current(loadedUser);\n \n // assuming you previous had var user = Ionic.User.current()\n // you will need to update your variable reference\n user = Ionic.User.current();\n};\n\nvar failure = function(error) {\n console.log('something went wrong');\n};\n\nIonic.User.load('user-id').then(success, failure);", "language": "javascript" } ] } [/block]