我有一个Angular服务,它接收一个数字N(在1-12之间)并返回整数之和,最多为12 - N:
app.value('myNumberService', {
calculateValue: function (n) {
var empty = [];
for(var i = 0; i < 12 - n; i++){
empty.push(i);
}
return empty;
}
});
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个非常基本的单元测试来检查服务是否已定义:
describe('app', function () {
var app, service;
beforeEach(function () {
app = angular.mock.module('app')
});
beforeEach(inject(function($injector) {
service = $injector.get('myNumberService');
}));
describe('*Validating myNumberService service', function () {
describe("calculateValue", function(){
it("should be defined.", function(){
expect(service.calculateValue()).toBeDefined();
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
PhantomJS 1.9.8 (Windows 7) app *Validating myNumberService service …Run Code Online (Sandbox Code Playgroud) jasmine angularjs angularjs-scope angular-services karma-jasmine
我有两个函数,我想在多个AngularJS控制器中共享,但我不确定如何为原型函数执行此操作.
以前,功能是在控制器中定义的:
Array.prototype.contains = function(needle) {
...
}
Run Code Online (Sandbox Code Playgroud)
这允许使用该contains方法链接任何数组.但是,当放置在工厂中时,这不起作用,因为contains未定义服务之外的任何阵列.
(function() {
'use strict';
angular
.module('app')
.factory('FunctionsFactory', FunctionsFactory);
function FunctionsFactory() {
return {
contains: contains,
exactlyContains: exactlyContains
};
...
Run Code Online (Sandbox Code Playgroud)
跨多个AngularJS控制器共享这些类型功能的最佳方法是什么?
如果我遵循这种制造工厂的特殊做法:
myApp.factory('myService', function () {
var somevalue = 2;
var myServiceApi = {
theValue: somevalue,
updatevalue: updateValue
}
return myServiceApi;
function updateValue(newValue) {
somevalue = newValue;
}
});
Run Code Online (Sandbox Code Playgroud)
每次注入服务时,值somevalue始终初始化为2,即使我之前使用UpdateValue方法更新了它.但是,如果我在值上使用getter方法,那么它将在服务的所有实例中更新.
http://jsfiddle.net/IngoVals/hd1r1bmp/
这背景是怎么回事?
我的角度服务有问题.
我的服务有下一个代码:
app.service("Utilidades", ['$http', '$window', function ($http, $window) {
return {
Get: function (urlAbsoluta, parametros, callback) {
var Utilidades = this;
$http
.get(app.UrlBase + urlAbsoluta, parametros)
.then(function (data) {
var Datos = angular.fromJson(data);
Utilidades.GuardarToken(Datos.Token);
callback(Datos);
});
},
ObtenerMenu: function () {
var Utilidades = this;
Utilidades.Get("Administracion/Api/Usuarios/Menu", {}, function (Datos) {
Datos = angular.fromJson(Datos.data);
if (Datos.Error == "") {
return Datos.Resultado;
} else {
return "";
}
});
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
然后,在我的控制器中,我有下一个代码:
app.controller('LoginCtrl', ['$scope', '$http', '$location', 'Utilidades',
function Iniciador($scope, $http, $location, …Run Code Online (Sandbox Code Playgroud) 产品服务.ts
getProduct(id: number): Observable<IProduct> {
return this._http.get(this._productUrl + '/GetById/' +
id).map((response: Response) => <IProduct>response.json())
.catch(this.errorHandler);
}
Run Code Online (Sandbox Code Playgroud)
产品详细信息组件.ts
getProduct(id: number) {
this._productService.getProduct(id).subscribe(
res => {
console.log('before component ' + res);
this.product = res;
console.log('after component ' + res);
},
error => this.errorMessage = <any>error),
console.log('execution complete');
}
Run Code Online (Sandbox Code Playgroud)
当在订阅中接收结果时,它会在
执行完成时出现,在组件 [object Object] 之前,在组件 [object Object] 之后
angularjs-directive angular-services angular2-routing angular
如果通常导致更改检测运行的事件(setTimeout、setInterval、浏览器事件、ajax 调用等)来自特定类(服务或组件),是否有办法完全禁用 Angular 的更改检测器?
也就是说,当我发现setInterval在我的服务中注册导致全局更改检测每秒运行时,这对我来说似乎是完全错误的。
我知道我可以将我的代码包装在NgZone.runOutsideAngular方法的回调中,但我更喜欢可以为整个类禁用更改检测器的解决方案,因为我在服务中还有其他代码块也不必要地运行检测.
谢谢你的帮助。
我正在使用Angular CLI。其实我有服务。该服务返回变量答案。我想在app-component中使用变量(或变量的重复)。因此,当答案更改时,必须在应用程序组件中看到它。现在我可以看到该变量的唯一初始值,而看不到更改后的答案。
服务:
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
@Injectable()
export class LogInGuardService implements CanActivate {
public answer: boolean;
public i: number = 0;
canActivate() {
let entered = JSON.parse(localStorage.getItem('enteredValue'));
let enteredEmail = entered.email_field;
let enteredPw = entered.password_field;
let guardChange = false;
for (var i = 1; i < localStorage.length; i++) {
let stored = JSON.parse(localStorage.getItem(localStorage.key(i)));
let storedEmail = stored.email_field;
let storedPw = stored.password_field;
if ( enteredEmail == …Run Code Online (Sandbox Code Playgroud) 嗨,我是 angular 2+ 的新手,我正在尝试在两个组件之间共享数据,但第二个组件没有从服务中检索数据,它获取了一个空对象。
服务 - 使用 rxjs BehaviorSubject 来保持对象
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class PostsService {
response: any = {};
private messageResponse = new BehaviorSubject(this.response);
currentResponse = this.messageResponse.asObservable();
constructor(private http: Http) { }
// Get all posts from the API
getAllPosts() {
return this.http.get('/api/posts')
.map(res => {
this.messageResponse.next(res.json());
return res.json();
}).catch(err => {
console.log('caught exception' + err.status);
return Observable.throw(err);
});
}
}
Run Code Online (Sandbox Code Playgroud)
组件 1 - 帖子。该组件首先调用获取数据,检索没有问题,并更新messageResponse。
export class PostsComponent …Run Code Online (Sandbox Code Playgroud) 我是angular 4中的一只新蜜蜂。我在服务“ data.service.ts”中编写了一个getDataMethod()方法。
现在,我想在html页面上单击“提交”按钮时调用此函数。
我们怎么称呼这个功能?请帮我。
我在组件的构造函数中创建了服务实例,如下所示
cnstructor(private dataservice: DataService){
this.data-service-method = this.dataservice.getDataMethod();
}
Run Code Online (Sandbox Code Playgroud) 我的项目角度有问题,但我不知道问题出在哪里。我想在我的项目中添加一项服务,因为我像这样定义了该服务
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
@Injectable
export class ContactService{
constructor(public http: Http){
}
getContacts(){
return this.http.get("http://localhost:8080/findPersons?
mc=wa&page=1&size=6").map(resp => resp.json());
}
}
Run Code Online (Sandbox Code Playgroud)
在我的 IDE 控制台中,我在 src/contact.service/contacts.service.ts(4,1) 中出现此错误:错误 TS1238:作为表达式调用时无法解析类装饰器的签名。
我也有同样的错误
有谁可以帮助我并谢谢你:)
angular-services ×10
angular ×6
angularjs ×4
rxjs ×2
typescript ×2
jasmine ×1
javascript ×1
observable ×1
promise ×1