Using Laravel 5.4 route in AngularJS $http service - angularjs

I'm using Laravel 5.4 and AngularJS. I have this function :
$scope.allPosts = function() {
$http.get("/posts")
.then(function(){
}, function(error){
});
};
How can I avoid using hardcoded "/posts" and instead using a Laravel route there ?
Thank you.

Simply share your routes variable on app as Json object and call them using a common function. but you should only share web app related routes.
view::share('routes',json_encode($routeArray));
in the header file of app
var routes = {{$routes}}
Create functions to access routes from routes.js
function getRoute(key) {
var results = fetchFromObject()
if(results === false){
return f
}else if (typeof results === 'undefined') {
return f
}else{
return results
}
}
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return false;
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
now call in your app getRoute('key')

You can use the laroute package to get Laravel's routes in your JS:
$http.get(laroute.route('posts'));

Related

Ionic App Onesignal Push Notification not able to redirect to specific page

I am trying to redirect to a specific job page when there's a new applicant.
Here's the code:
app.run(function($ionicPlatform, $location) {
$ionicPlatform.ready(function() {
if (ionic.Platform.isWebView()) {
window.plugins.OneSignal
.startInit("xxxxxxxxxxxxxx", "xxxxxxxxxxxx")
.handleNotificationReceived(function(jsonData) {
console.log("/app/upcoming/" + jsonData.payload.additionalData.url);
$location.path("/app/upcoming/" + jsonData.payload.additionalData.url);
})
.endInit();
}
The console shows the correct address but it does not redirect or have any errors.
For Ionic you will need to use $state.go to redirect the user to a different page in your app.
var notificationOpenedCallback = function(result) {
var data = result.notification.payload.additionalData;
if (data && data.targetUrl) {
var state = $injector.get($state);
state.go(data.targetUrl);
}
};
window.plugins.OneSignal
.startInit("YOUR_APPID", "YOUR_GOOGLE_PROJECT_NUMBER_IF_ANDROID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();

How to refresh the view when angular $http promise call wrapped in rxjs Observable

I have a project that uses angular's $http service to load data from a remote location. I want to use rxjs Observables so the call in my service looks like this:
userInfo() : Rx.Observable<IUserInfo> {
var url : string = someUrl + this._accessToken;
return Rx.Observable.fromPromise<IUserInfo>( this.$http.get<IUserInfo>( url ) );
}
and this is subscribed to by my controller like this:
getUserInfo() : void {
this._googleService.userInfo().subscribe(
( result ) => { this.handleUserInfo( result ) },
( fault : string ) => this.handleError( fault )
)
}
private handleUserInfo( result : IHttpPromiseCallbackArg<IUserInfo> ) : void {
console.log( "User info received at " + new Date() );
this._name = result.data.given_name + " " + result.data.family_name;
this._email = result.data.email;
this._profilePicUrl = result.data.picture;
}
the problem is that despite the name, email and profile pic being updated these changes are not visible. As soon as anything else triggers an angular $apply the changes appear but because of the Observable these changes in the controller happen after the angular digest loop that is triggered by the $http call.
This does work correctly if my service just returns a promise to the controller.
How do I update my view in this case? I do not want to manually have to wire up each observable to trigger a digest cycle. I want all Observables to trigger a digest cycle when they receive a new value or error.
We can use the ScopeScheduler from rx.angular.js for this. We only have to create a new one where we create our angular module and pass the $rootScope to it:
const module : ng.IModule = angular.module( 'moduleName', [] );
module.run( ["$rootScope", ( $rootScope ) => {
new Rx.ScopeScheduler( $rootScope );
}]);
That's all you have to do. Now all Rx.Observables trigger an $apply when they get a new value.
For some reason the ScopeScheduler was deleted when the rx.angular.js library was upgraded to rxjs version 4. We have to use rx.angular.js version 0.0.14 to use the ScopeScheduler.
I do not know what the suggested solution to this is in version 4.
A project using this fix can be viewed here:
https://github.com/Roaders/Typescript-OAuth-SPA/tree/observable_apply_issues
I couldn't get the Rx.ScopeScheduler method to work, so I just overwrote the rx observable subscribe method itself instead, and wrapped the callbacks in $rootScope.$apply :)
module.run(['$rootScope', 'rx', function ($rootScope, rx) {
rx.Observable.prototype.subscribe = function (n, e, c) {
if(typeof n === 'object') {
return this._subscribe(n);
}
var onNext = function(){};
if(n) {
onNext = function(value) {
if($rootScope.$$phase) {
n(value);
}
else {
$rootScope.$apply(function(){ n(value); });
}
};
}
var onError = function(err) { throw err; };
if(e) {
onError = function(error) {
if($rootScope.$$phase) {
e(error);
}
else {
$rootScope.$apply(function(){ e(error); });
}
};
}
var onCompleted = function(){};
if(c) {
onCompleted = function() {
if($rootScope.$$phase) {
c();
}
else {
$rootScope.$apply(function(){ c(); });
}
};
}
return this._subscribe(
new rx.AnonymousObserver(onNext, onError, onCompleted)
);
};
}]);

How to add dynamic open routes in Angular?

In my Angular app I a restricting redirects with the following code within run() in my app.js
var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
I would want to add /route/action/:myParameter also to be added as a part of login and register, where myParameter is a variable.
Is there a way I can achieve this?
If you want to do this manually, you can run the following against the $location.path() variable.
var toFind = '/route/action/'
var path = $location.path()
if (path.substring(0, toFind.length) === toFind) {
var myParameter = path.substring(toFind.length)
...
}
If you have more than one route like this however, consider using angular-route, which allows nicer syntax, eg:
routeProvider.when('/route/action/:myParameter', ...)

AngularJs get route by URL

Is there a way to get route by URL??
What I mean is I have a route /users/:id, I am getting route object using $route
var route_object = ($route.routes['/users/:id']);
But is it possible to get route with this URL /users/5
So when I try
var route_object = ($route.routes['/users/5']);
I am getting undefined value.
No, there is no build-in way to get a route object by corresponding url. However it's pretty easy to do with few lines of code. The idea is to test url against routes regular expressions:
var url = '/users/5/';
for (var path in $route.routes) {
if ($route.routes[path].regexp && $route.routes[path].regexp.test(url)) {
console.log('found route:', $route.routes[path]);
}
}
You can wrap it in helper function and put in in some util service maybe or controller:
function getRouteByUrl(url) {
for (var path in $route.routes) {
if ($route.routes[path].regexp && $route.routes[path].regexp.test(url)) {
return $route.routes[path];
}
}
return null;
}

Disable template caching in AngularJS with ui-router

I have noticed that from time to time I'll make a change to one of the templates within my AngularJS application and that at runtime, the change won't be visible. Rather, I'll have to refresh the application and if that fails, go to the path of the template itself and refresh it in order to see this change.
What's the best way to prevent caching of these templates like this? Ideally, I'd like them to be cached during the current use of the Angular application, but that the next time I load the page, they retrieve the latest and greatest templates without having to manually refresh.
I'm using ui-router if that makes any difference here. Thanks!
You can use a decorator and update UI Router's $templateFactory service to append a suffix to templateUrl
function configureTemplateFactory($provide) {
// Set a suffix outside the decorator function
var cacheBuster = Date.now().toString();
function templateFactoryDecorator($delegate) {
var fromUrl = angular.bind($delegate, $delegate.fromUrl);
$delegate.fromUrl = function (url, params) {
if (url !== null && angular.isDefined(url) && angular.isString(url)) {
url += (url.indexOf("?") === -1 ? "?" : "&");
url += "v=" + cacheBuster;
}
return fromUrl(url, params);
};
return $delegate;
}
$provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}
app.config(['$provide', configureTemplateFactory]);
Above solution was great and was not working for template urls
function templateUrl: function($stataParams) { return '/serverUrl?id=' + $stataParams.id + '&cid=' + $stataParams.cid; }
fixed by
function templateFactoryDecorator($delegate) {
var fromUrl = angular.bind($delegate, $delegate.fromUrl);
$delegate.fromUrl = function (url, params) {
if (url !== null && angular.isDefined(url)) {
if (typeof url == 'function') {
url = url.call(url, params);
}
if (angular.isString(url)) {
url += (url.indexOf("?") === -1 ? "?" : "&");
url += "v=" + Date.now().toString();
}
}
return fromUrl(url, params);
};
return $delegate;
}

Resources