gpt4 book ai didi

javascript - 将 Angular 服务放入应用程序配置中

转载 作者:行者123 更新时间:2023-12-03 08:06:11 26 4
gpt4 key购买 nike

app.js

        angular
.module('yelp',['ngRoute']) //creating module
.config(config);

config.$inject=['$routeProvider','YelpService']; //YelpService is unknown here
function config($routeProvider){

$routeProvider
.when('/restaurants',{
templateUrl:'partials/restaurants.html',
controller:'RestaurantsController',
controllerAs:'rstrntsCtrl',
resolve:{
getRestaurants:getRestaurants
}
});
}

function getRestaurants(YelpService){
// i need route params here
}

YelpService.js

    angular
.module('yelp') //using already created module
.factory('YelpService',YelpService);

YelpService.$inject=['$http'];
function YelpService($http){

var factory={
}

return factory;
}

我首先加载了 app.js 文件,然后加载了 yelpService.js 文件。由于服务稍后加载,我认为它无法注入(inject)。如果我首先加载服务文件,则会导致错误,因为模块是在配置文件中创建的。如何克服这个问题。此外,在配置文件中如何在 getRestaurants 方法中获取路由参数

最佳答案

对于 yelp,请使用提供程序调用 YelpServiceProvider。对于解析,只需包装在一个函数中并注入(inject)所需的功能。

angular
.module('yelp',['ngRoute']) //creating module
.config(config);

config.$inject=['$routeProvider','YelpServiceProvider']; //YelpService is unknown here
function config($routeProvider){

$routeProvider
.when('/restaurants',{
templateUrl:'partials/restaurants.html',
controller:'RestaurantsController',
controllerAs:'rstrntsCtrl',
resolve:{
restaurants:function($routeParams, YelpService) {
return getRestaurants($routeParams, YelpService);
}
}
});
}

function getRestaurants($routeParams, YelpService){
// i need route params here
}

Resolve 用于解析您的数据。因此,左边的赋值不会是您可能想要的函数名称,而是变量项目列表(实际上是一个 promise )。

然后在注入(inject)“餐馆”后在 Controller 中:

this.restaurants; // or $scope.restaurants if you are not using controllerAs

关于javascript - 将 Angular 服务放入应用程序配置中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com