我正试图在我的应用程序中实现一个auth guard.即; 只有经过身份验证的用户才能访问我的应用的某些路由 我跟着这里给出的啧啧.
一旦用户登录,我将我的AuthService中的布尔值更改为true以指示该用户已登录.这需要在应用程序的整个生命周期中保留.
下面给出了源代码:
AUTH-guard.service.ts
import { Injectable } from '@angular/core';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
console.log('Auth Guard Service: ' + this.authService.isLoggedIn);
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for …Run Code Online (Sandbox Code Playgroud) 我正在使用Angular 2来构建我的Web应用程序,其中包含许多组件.我正在使用angular-cli来创建,运行和构建项目.
偶然(或幸运)我偶然发现了一个错误,我意识到我的组件的多个实例正在创建.更糟糕的是当我意识到我的代码是随机引用任何一个这样的实例而没有任何逻辑来追溯它.
Date.now()console.log()语句,告诉我哪个实例是由我的变量的值调用的.
这是我的日志声明的图像.我已经把敏感部分搞砸了.可以清楚地看到,一些休息呼叫正在使用租户1的唯一ID,而一些用于试用租户.从两个实例时间也可以非常清楚地使用两个实例.以前登录的租户的旧实例在某种程度上仍在使用中,我的组件仍然可以访问它.
这是我的代码:
public class RouteSingleton
{
private IDictionary<string, string> _dealCatLinks;
private IDictionary<string, string> _sectionLinks;
private IDictionary<string, string> _categoryLinks;
private IDictionary<string, string> _materials;
private IDictionary<string, string> _vendors;
public RouteSingleton(IDealService dealService
, ICategoryService categoryService
, IVendorService vendorService)
{
this._dealCatLinks = dealService.GetDealCatLinks("PLV").Distinct().ToDictionary(x => x, x => x);
this._sectionLinks = categoryService.GetSectionLinks("PLV").Distinct().ToDictionary(x => x, x => x);
this._categoryLinks = categoryService.GetMainCategoryLinks("PLV")
.Where(x => !_sectionLinks.ContainsKey(x)).Distinct().ToDictionary(x => x, x => x);
this._vendors = _vendorService.GetVendorLinks("PFB").Distinct().ToDictionary(x => x, x => x);
}
public bool IsDealCategory(string slug)
{
return _dealCatLinks.ContainsKey(slug);
}
public …Run Code Online (Sandbox Code Playgroud) 情况就是这样:我的课程做得太多了.它主要用于访问配置信息,但它也具有数据库连接.它是作为一个单独实现的,所以这也使单元测试变得困难,因为大多数代码与它紧密耦合.这甚至更成问题,因为它创建了一个导入时间依赖项(我们在Python中这样做),这意味着某些模块必须按特定顺序导入.理想情况下,我想将它分成两个类,并使其成为非单例.
幸运的是,我的雇主已经热心这样一个事实,即这种测试是好的,如果它使代码更容易测试,我愿意允许我做这样的改变.但是,我怀疑他们是否愿意让我花太多时间在上面.而且我宁愿逐步修复它,而不是试图过于激进.
所以,我在这里看到三个选择:
那我该怎么办?
我正在学习Python,并且我一直在尝试将Singleton类型的类作为测试.我的代码如下:
_Singleton__instance = None
class Singleton:
def __init__(self):
global __instance
if __instance == None:
self.name = "The one"
__instance = self
else:
self = __instance
Run Code Online (Sandbox Code Playgroud)
这部分工作,但self = __instance部分似乎失败了.我已经包含了解释器的一些输出来演示(上面的代码保存在singleton.py中):
>>> import singleton
>>> x = singleton.Singleton()
>>> x.name
'The one'
>>> singleton._Singleton__instance.name
'The one'
>>> y = singleton.Singleton()
>>> y.name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
<type 'instance'>
>>> dir(y)
['__doc__', '__init__', '__module__']
Run Code Online (Sandbox Code Playgroud)
有可能做我正在尝试的事情吗?如果不是,还有另一种方法吗?
欢迎任何建议.
干杯.
我正在开发ASP.NET应用程序,我有EF 4.0模型的问题.
EF模型检测新添加和删除的数据,但不检测数据库中的修改数据.
这是我所拥有的问题的一个例子.
A-数据库:
用于生成"Employees"数据库表的脚本
CREATE TABLE [dbo].[Employees]
(
[id] [int] IDENTITY(1, 1)
NOT NULL,
[name] [nvarchar](50) NULL,
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED ( [id] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
)
ON [PRIMARY]
Run Code Online (Sandbox Code Playgroud)
B-应用:
以下是示例项目的链接Click Here.
重现错误的步骤:
1-创建数据库并运行脚本以创建表.
2-在employees表中插入测试数据,然后运行该应用程序.数据将加载到默认页面中.
3-更改连接字符串并运行应用程序.
3-更新数据库中的某些值(直接形成sql).并刷新页面
您会发现应用程序仍然显示旧数据,而如果您从表中添加或删除项目,则分别在视图中添加或删除它.
在此先感谢您的帮助.
我有一个用于许多单例实现的通用接口.接口定义了可以抛出检查异常的初始化方法.
我需要一个工厂,它将按需返回缓存的单例实现,并想知道以下方法是否是线程安全的?
更新1:请不要建议任何第3部分图书馆,因为这可能需要获得法律许可,因为可能的许可问题:-)
更新2:此代码可能会在EJB环境中使用,因此最好不要生成其他线程或使用类似的东西.
interface Singleton
{
void init() throws SingletonException;
}
public class SingletonFactory
{
private static ConcurrentMap<String, AtomicReference<? extends Singleton>> CACHE =
new ConcurrentHashMap<String, AtomicReference<? extends Singleton>>();
public static <T extends Singleton> T getSingletonInstance(Class<T> clazz)
throws SingletonException
{
String key = clazz.getName();
if (CACHE.containsKey(key))
{
return readEventually(key);
}
AtomicReference<T> ref = new AtomicReference<T>(null);
if (CACHE.putIfAbsent(key, ref) == null)
{
try
{
T instance = clazz.newInstance();
instance.init();
ref.set(instance); // ----- (1) -----
return instance;
}
catch (Exception …Run Code Online (Sandbox Code Playgroud) 我在Java采访中得到了下一个问题:
你能说出现实生活中的一些通用类例吗?不是来自真正的PROGRAMMING生活,而是共同的.例如,您正在向人们解释泛型,他们对编程一无所知.
关于最简单的设计模式 - 单身人士也是如此.
我知道任何想法,关于第一个问题(关于泛型),我试图命名不同的手工工具(如fretsaw),它只使用一种类型的材料,但它不是真正的泛型.
请避免像收集一样的建议,这太天真和明显了.
这是一个简单的单身人士:
class Singleton
{
Singleton();
virtual ~Singleton();
Singleton * Singleton::getInstance()
{
static Singleton * instance;
if (!instance) {
instance = new Singleton();
};
return instance;
};
}
Run Code Online (Sandbox Code Playgroud)
当主代码Singleton::getInstance()->someMethod()第一次调用时,是不是实例化了两次类?会有内存泄漏吗?
我问,因为Visual Leak Detector检测到线路上的内存泄漏new Singleton().
我需要在一个组件(组件A)中设置值并在另一个组件(组件B)中接收值.组件A和组件B不是父级和子级.
我创建了一个共享服务来共享两个组件之间的数据.我能够从组件B设置值,但是当我订阅以获取组件A中的值时,它不会被触发.
这是我尝试过的:
我@NgModule providers在appmodule.ts文件中添加了Service in array,以便它可用于项目中的所有组件.
服务代码:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from '../../node_modules/rxjs';
@Injectable({
providedIn: 'root'
})
export class SocialService {
constructor() { }
private valueObs: BehaviorSubject<string> = new BehaviorSubject<string>(null);
public setValue(value: string):void {
this.valueObs.next(value);
this.getValue();
}
public getValue():Observable<string> {
return this.valueObs;
}
}
Run Code Online (Sandbox Code Playgroud)
组件B:此处设置值
@Component({
selector: 'app-componentb',
templateUrl: './componentb.component.html',
styleUrls: ['./componentb.component.scss']
})
constructor(private socialService: SocialService, private http: HttpClient) {
}
buttonClick()
{
this.socialService.setValue("linked successfully");
}
Run Code Online (Sandbox Code Playgroud)
组件A: …
singleton ×10
angular ×3
java ×2
oop ×2
asp.net-core ×1
atomic ×1
c# ×1
c++ ×1
caching ×1
callback ×1
factory ×1
generics ×1
god-object ×1
injectable ×1
memory-leaks ×1
python ×1
readonly ×1
static ×1
typescript ×1