我是Angular2和Rxjs的新手,我对某个特定案例有点困惑.
我有一个简单的服务:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { Http, Response } from '@angular/http';
export interface Article {
id: number;
title: string;
content: string;
author: string;
}
@Injectable()
export class ArticleService {
private _articles$: Subject<Article[]>;
private baseUrl: string;
private dataStore: {
articles: Article[]
};
constructor(private http: Http) {
this.baseUrl = 'http://localhost:3000'
this.dataStore = { articles: [] };
this._articles$ = <Subject<Article[]>>new Subject();
}
get articles$(){
return this._articles$.asObservable();
}
loadAll(){
//Observable.from(this.dummyData)
this.http.get(`${this.baseUrl}/articles`)
.map(response => …Run Code Online (Sandbox Code Playgroud) 我今天刚刚将我的应用程序切换为延迟加载.
我有一个SharedModule导出一堆服务.在我AppModule,我导入SharedModule因为AppComponent需要访问一些共享服务.
在另一个模块中FinalReturnModule,我导入SharedModule.在我的一个服务中,我console.log('hi')在构造函数中添加了一个.
当应用程序首次加载时,我会hi进入控制台.每当我导航到我内心的页面时,FinalReturnModule我会hi再次进入.显然,由于有两个实例,因为模块无法通信,所以没有任何工作正常.
如何阻止服务实例化两次?
编辑:背景,该应用程序使用angular-cli构建.
当前版本:
angular-cli: 1.0.0-beta.24
node: 6.9.1
os: win32 ia32
@angular/common: 2.4.1
@angular/compiler: 2.4.1
@angular/core: 2.4.1
@angular/forms: 2.4.1
@angular/http: 2.4.1
@angular/platform-browser: 2.4.1
@angular/platform-browser-dynamic: 2.4.1
@angular/router: 3.1.1
@angular/compiler-cli: 2.4.1
Run Code Online (Sandbox Code Playgroud) 我使用index.ts文件封装出口,如角度2样式指南(https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure)中所述.
这在我写的应用程序中运行良好,但由于某种原因,在一个服务中,我试图注入另一个服务,这会导致一个奇怪的错误.
导出的类:
import {Injectable} from "angular2/core";
@Injectable()
export class UserIds{
private _signature_id:string;
private _role_id:number;
get signature_id():string{
return this._signature_id;
}
set signature_id(id:string){
this._signature_id = id;
}
get role_id():number{
return this._role_id;
}
set role_id(id:number){
this._role_id = id;
}
}
Run Code Online (Sandbox Code Playgroud)
index.ts文件:
export {Midiate} from "./midiate.service/midiate.service";
export {HttpRest} from "./http_rest.service/http_rest.service";
export {UserIds} from "./user_ids.service/user_ids.service"
Run Code Online (Sandbox Code Playgroud)
导致错误的代码(导入文件):
import {UserIds} from "../index";
import {Http} from 'angular2/http';
@Injectable()
export class HttpRest{
constructor(
public _http: Http,
public userIdsx: UserIds
){}
...
}
Run Code Online (Sandbox Code Playgroud)
浏览器抛出的错误:
EXCEPTION: Cannot resolve …Run Code Online (Sandbox Code Playgroud) 我得到一个No Provider for FirebaseService甚至自举后,错误FirebaseService的bootstrap(app, [providers])方法.
我按照Pascal的指南在服务中注入Http服务,当我使用HTTP_PROVIDERS引导程序注入服务时它工作,但是No providers for FirebaseService在将它更改为我自己的服务后收到错误.
我可以通过删除正常的注射来单独注射两个提供者FirebaseService.即使我这样做contructor(@Inject(FirebaseService) firebase: FirebaseService){}也行不通,但我的理解是添加@Injectable()装饰器应该具有相同的效果.
登录-page.ts
import {Component} from '@angular/core';
import {UserService} from '../../Services/user.service';
import {FirebaseService} from '../../services/firebase.service';
import { UserModel } from '../../export';
@Component({
moduleId: 'app/PAGES/login-page/',
selector: 'login-page',
templateUrl: 'login-page.html',
styleUrls: ['login-page.css'],
providers: [ UserService]
})
export class LoginPage {
constructor(private userService: UserService) {}
user:UserModel = new UserModel();
hello: string = "You …Run Code Online (Sandbox Code Playgroud) 在Angular 2 RC 4中,我有一个类HttpLoading,它扩展了Angular 2的原始Http服务.
使用RC 4,我可以使用以下代码在bootstrap中使用它而没有任何问题:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(RequestOptions, { useClass: DefaultRequestOptions }),
provide(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new HttpLoading(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
})
]).catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
我的DefaultRequest选项类
import { Injectable } from '@angular/core';
import { Headers, BaseRequestOptions } from '@angular/http';
@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {
headers: Headers = new Headers({
'Content-Type': 'application/json'
});
}
Run Code Online (Sandbox Code Playgroud)
我的HttpLoading类看起来像这样:
import { Http, RequestOptionsArgs, ConnectionBackend, RequestOptions, Response } from '@angular/http'
import { Injectable } from '@angular/core' …Run Code Online (Sandbox Code Playgroud) 我决定将LoginComponent,AuthService,LoggedInGuard放在一个名为AuthModule的模块中:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthComponent } from './auth.component';
import { LoginComponent } from './components/login/login.component';
import { AuthService } from './services/auth/auth.service';
import { StorageService } from './services/storage/storage.service';
import { RequestService } from './services/request/request.service';
import { LoggedInGuard } from './guards/logged-in.guard';
@NgModule({
imports: [
CommonModule
],
providers: [AuthService, LoggedInGuard],
declarations: [AuthComponent, LoginComponent],
exports: [AuthService, LoggedInGuard]
})
export class AuthModule { }
Run Code Online (Sandbox Code Playgroud)
我想在Application的其余部分中仅使用AuthService方法.和LoggedInGuard保护非公共路线.
所以我尝试在AppModule中导入它们:
import { AuthModule } from './core/auth/auth.module';
@NgModule({
declarations: [AppComponent, …Run Code Online (Sandbox Code Playgroud) 我有一个Angular2应用程序,它需要支持多种语言.其中一些语言可能是RTL(即波斯语),有些语言可能是LTR(即英语).除了本地化字符串之外,我还需要根据语言的方向设置组件的样式.
现在使用这个帮助器,我可以有两个单独的文件(即app-rtl.scss和app-ltr.scss),它们都导入一个scss文件(即app.scss),它允许我在一个地方写我的scss代码,自动输出两个文件; 每个方向一个.
问题是现在我需要以某种方式根据用户的语言引用合适的css文件.因此,如果用户的语言是英语,然后我应该
<link href="app-ltr.css" rel="stylesheet">在头,如果它是RTL, <link href="app-rtl.css" rel="stylesheet">.此外,我想为我的项目添加bootstrap,并且还有两个不同的LTR和RTL输出文件.
有没有干净的方法来实现这个功能?
我创建了两个虚拟组件(一个用于LTR,一个用于RTL),没有任何模板,然后分配相应的scss文件styleUrls并设置encapsulation: ViewEncapsulation.None为使其成为全局样式.然后我使用*ngIf在我的根组件模板中初始化它们,并检查语言是否为LTR.
这将适用于第一页加载,因为只有一个组件(比如组件LTR)处于活动状态,但只要您更改语言(即第二个组件(RTL)变为活动状态并因此删除了LTR),则与之关联的样式LTR停留在页面上,不会被删除.那么你的页面上既有RTL又有LTR样式,而不是你想要的.
我正在打电话给你,要求你在这里使用什么方法:我已经测试了许多东西来解决我的问题,我至少有4个工作解决方案,但我不知道哪一个是最好的,如果其中一些只是因为我所做的其他事情的副作用而工作,不应该使用...
我在文档中找不到任何指向这些解决方案(或另一个)的解决方案
首先,这是我的情况:我正在构建一个连接到数据API的应用程序,并构建不同的部分,每个部分包含dataviz.
我将站点的各个部分构建为模块,但它们共享一个名为DataService的服务(这些模块中的每一个都将使用DataService来获取和处理数据).
我的DataService需要一个配置文件,其中包含许多特定于每个部分的选项,并存储在它自己的文件夹中.
因此,我需要在module.ts文件的providers部分中为每个部分单独提供DataService,并且避免将DataService复制到每个模块似乎是一种好习惯...
所以文件的架构是:
--Dashboard module
----data.service.ts
----Section1 module
------Section1 config file
----Section2 module
------Section2 config file
Run Code Online (Sandbox Code Playgroud)
我尝试了多个似乎在部分模块文件中工作的东西:
解决方案1:注射
(即使我没有在任何地方看到这种情况,我也无法在没有引号的情况下使注射工作)
模块文件:
import { DataService } from '../services/data.service';
import viewConfig from './view.config.json';
@NgModule({
imports: [ ... ],
declarations: [ ... ],
providers: [
{ provide: 'VIEW_CONFIG', useValue: viewConfig },
DataService,
]})
export class Section1Module { }
Run Code Online (Sandbox Code Playgroud)
部分文件:
@Injectable()
export class DataService {
constructor(@Inject('VIEW_CONFIG') private viewConfig : any) {}
}
Run Code Online (Sandbox Code Playgroud)
解决方案2:工厂提供商
ng服务重启后无法正常工作(请参阅更新)
灵感来自https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#factory-provider
模块文件:
import { DataService …Run Code Online (Sandbox Code Playgroud) 我一直在试图找出的意义ngAfterContentChecked(),并 ngAfterViewChecked()在一段时间.曾尝试过各种帖子,但仍无法理解其确切含义.以下是angular.io中给出的定义.有人可以用一些好的例子来解释它.
ngAfterViewChecked()- Respond after Angular checks the component's views and child views.
Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
A component-only hook.
ngAfterContentChecked()- Respond after Angular checks the content projected into the component.
Called after the ngAfterContentInit() and every subsequent ngDoCheck().
A component-only hook.
Run Code Online (Sandbox Code Playgroud) 我在项目中使用ngx bootstrap datepicker
仅需要像上面的图像一样选择月份和年份
<input type="text"
class="form-control"
(bsValueChange)="modelChanged($event)"
#dp="bsDatepicker"
bsDatepicker [(bsValue)]="bsValue"
[bsConfig]="{ dateInputFormat: 'YYYY-MM-DD' }"
>
Run Code Online (Sandbox Code Playgroud)
有没有办法像这样配置日期选择器?或建议任何允许此功能的替代日期选择器