我使用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) 我基本上想要创建一个自定义对话框组件,我可以在我的Angular2应用程序中的任何位置使用它,无论应用程序树中的using组件位于何处.为简单起见,我们称之为SayHello组件.
所以,假设我想要SomeComponent.level3.component来调用SayHello.component中的对话框.
在Angular 1.x中,我会将RootScope注入控制器并以此方式点亮对话框.现在,我了解(或多或少)对于Angular2,你可以在组件树上冒泡事件(使用事件发射器),但是从树上的SomeComponent.level3.component向下到SayHello一直冒泡一个事件似乎很乏味. .零件.
所以我想我会创建一个SayHello服务,我会在任何想要点亮对话框的地方注入.这是我制定的代码草图.
myApp.component.ts
import {SayHelloComponent} from "<<folder>>/sayHello.component";
import {BunchOfComponents} from "<<folder>>/bunchOfComponents";
@Component({
directives: [SayHelloComponent],
selector: "my-app",
templateUrl: `<bunch-of-components>Within this component exists
SomeComponent.level3.component </bunch-of-components>
<say-hello showdialog="{{showDialog}}" message="{{message}}">
</say-hello>`
})
export class myAppComponent {
showDialog = false;
message = "";
constructor(private sayHelloService: SayHelloService) {
this.showDialog = sayHelloService.showDialog;
this.message = sayHelloService.message;
}
}
Run Code Online (Sandbox Code Playgroud)
SayHelloService.ts
import {Injectable} from 'angular2/core';
@Injectable()
export class SayHelloService {
public showDialog: boolean = false;
public message: string ="";
constructor() { …Run Code Online (Sandbox Code Playgroud) 因此,我尝试使用JSON Web令牌进行身份验证,并且正在努力弄清楚如何将它们附加到标头并根据请求发送它们.
我试图使用https://github.com/auth0/angular2-jwt,但我无法使用Angular并放弃,并认为我可以弄清楚如何在每个请求中发送JWT或发送它在标题中(最好是标题).它比我想象的要困难一点.
这是我的登录
submitLogin(username, password){
console.log(username);
console.log(password);
let body = {username, password};
this._loginService.authenticate(body).subscribe(
response => {
console.log(response);
localStorage.setItem('jwt', response);
this.router.navigate(['UserList']);
}
);
}
Run Code Online (Sandbox Code Playgroud)
和我的login.service
authenticate(form_body){
return this.http.post('/login', JSON.stringify(form_body), {headers: headers})
.map((response => response.json()));
}
Run Code Online (Sandbox Code Playgroud)
我知道这些并不是真的需要,但也许它会有所帮助!一旦这个令牌被创建并存储它,我想做两件事,在标题中发送它并提取我用它放入的过期日期.
一些Node.js登录代码
var jwt = require('jsonwebtoken');
function createToken(user) {
return jwt.sign(user, "SUPER-SECRET", { expiresIn: 60*5 });
}
Run Code Online (Sandbox Code Playgroud)
现在我只是尝试通过角度服务将其传递回使用此服务的节点.
getUsers(jwt){
headers.append('Authorization', jwt);
return this.http.get('/api/users/', {headers: headers})
.map((response => response.json().data));
}
Run Code Online (Sandbox Code Playgroud)
JWT是我在本地存储中的webtoken,我通过我的组件传递给服务.
我没有任何错误,但当它到达我的节点服务器时,我从来没有在标头中收到它.
'content-type': 'application/json',
accept: '*/*',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'en-US,en;q=0.8', …Run Code Online (Sandbox Code Playgroud) 根据我的理解Angular 2 rc5,要从另一个模块(不是AppModule)作为单个模块提供服务到每个组件,即使是那些延迟加载的模块,我们也不会将该服务包含在该providers模块的其他模块中.我们改为导出它RouterModule.forRoot()并导入结果AppModule
根据文件:
SharedModule应仅在根AppModule导入时提供UserService.SharedModule.forRoot方法帮助我们应对这一挑战...... SharedModule没有
providers...当我们将SharedModule添加到AppModule的导入时,我们调用forRoot.这样,AppModule获得导出的类,SharedModule同时提供单例UserService提供程序
我真的很挣扎如何为延迟加载的路由提供第三方服务(imports我的数组中的模块使用的服务AppModule).我无法控制这个第三方模块,所以我不能只从该NgModule.providers模块的数组中删除该服务,并将其放入RouterModule.forRoot()我的服务中.
具体的服务MdIconRegistry,这是providers对MdIconModule的Angular Material 2 alpha 7-3.此服务用于注册svg图标,然后可以使用<md-icon svgIcon='iconName'>标记显示在页面上.所以:
MdIconModule在我的根目录中导入AppModuleAppComponent该图标可见并且运行良好,但仅限于启动时加载的模块.延迟加载的模块无法看到这些图标,因此我怀疑Angular注入器不会注入相同的MdIconRegistry服务实例.
tl; dr:我怎样才能从第三方模块中将服务作为我的延迟加载组件的单例?
这是一个演示问题的编码器(编码typescript).
我在官方文档和网络上都没有发现 Angular 2 服务是否支持生命周期挂钩的信息。大多数钩子没有意义,但至少ngOnInit()可以非常有用。
实验表明ngOnInit()on an@Injectable()导致服务在引导过程中被实例化,即使它没有用户,但它没有被调用。下面是代码演示:
import { NgModule, Inject, Injectable, OnInit, Component } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
@Component({
template: 'test',
selector: 'my-component'
})
export class MyComponent {
}
@Injectable()
export class MyService /*implements OnInit*/ {
constructor() {
console.debug('constructing MyService');
}
ngOnInit(): void {
console.debug('MyService.ngOnInit');
}
}
@NgModule({
imports: [ BrowserModule ],
providers: [
MyService
],
declarations: [MyComponent],
bootstrap: [ MyComponent ]
})
class …Run Code Online (Sandbox Code Playgroud) 我想将我从Web API响应收到的XML转换为Angular 2中的JSON.该应用程序是在Nativescript中开发的.无法找到解决方案.
我的Angular 2应用程序具有注销功能.如果我们可以(即document.location.href = '/';),我们希望避免执行页面重新加载,但是注销过程需要重置应用程序,以便当另一个用户登录时,前一个会话中没有剩余数据.
这是我们的main.ts文件:
import 'es6-shim/es6-shim';
import './polyfills';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { ComponentRef, enableProdMode } from '@angular/core';
import { environment } from '@environment';
import { AppModule } from './app/app.module';
if (environment.production === true) {
enableProdMode();
}
const init = () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.then(() => (<any>window).appBootstrap && (<any>window).appBootstrap())
.catch(err => console.error(err));
};
init();
platformBrowserDynamic().onDestroy(() => {
init();
});
Run Code Online (Sandbox Code Playgroud)
您可以看到我在销毁应用程序时尝试调用init()方法.我们的user-authentication.service中的logout方法启动destroy:
logout() {
this.destroyAuthToken();
this.setLoggedIn(false);
this.navigateToLogin()
.then(() => {
platformBrowserDynamic().destroy();
});
}
Run Code Online (Sandbox Code Playgroud)
这会出现以下错误:
选择器"app-root"与任何元素都不匹配
任何帮助赞赏.
在Angular2中,基于第一个API调用的结果实现第二个API调用的正确方法是什么?我的一个Angular2组件有以下方法.我尝试在另一个订阅内完成订阅,第二个订阅的响应始终是"未定义".
根据CozyAzure的建议进行编辑.
export interface Result {
host: string;
resourceUri: string;
groupId?: string;
resource?: any;
}
private curateResults(searchTerm: string, searchResults: SearchResults): Result[] {
const results: Result[] = [];
if (searchResults.results !== undefined && searchResults.results.length > 0) {
searchResults.results.forEach((result: any) => {
const processedSearchResult: Result = {
host: result.origin.toString(),
resourceUri: result.url.toString()
};
processedSearchResult.resource = undefined;
processedSearchResult.groupId = undefined;
this.bopsHttpService.getResourceData(processedSearchResult.host, processedSearchResult.resourceUri)
.flatMap((resource: any) => {
processedSearchResult.groupId = this.getGroupIdFromResource(resource, 'groupId');
if (processedSearchResult.groupId === undefined) {
const uriParts = processedSearchResult.resourceUri.split('/');
const predicate = uriParts[uriParts.length - …Run Code Online (Sandbox Code Playgroud) 我还在学习angular2.我正在尝试学习如何使用WSDL将SOAP请求发送到Web服务.我正在寻找一些例子并找到一个.我创建了一个按钮,并希望调用该soap函数,以便在单击时向服务器发送请求.该项目已成功构建,但该功能不起作用.
app.component.ts
import { Component } from '@angular/core';
import { Http, Response, RequestOptions, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
declare var angular: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
soapCall() {
angular.module('myApp', ['angularSoap']);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://localhost/webservices/voltage-info-service/server/server.php', true);
//the following variable contains my xml soap request (that you can get thanks to SoapUI for example)
var sr = 'YEAH';
// '<?xml version="1.0" encoding="utf-8"?><lfc:requests><lfc:request><lfc:busID>66</lfc:busID><lfc:timestamp>223456789</lfc:timestamp><lfc:coordinates>'+
// '<lfc:LongD>8</lfc:LongD><lfc:LongM>6</lfc:LongM><lfc:LongS>25.599</lfc:LongS><lfc:LatD>51</lfc:LatD><lfc:LatM>33</lfc:LatM><lfc:LatS>23.9898</lfc:LatS>'+
// '</lfc:coordinates></lfc:request></lfc:requests>';
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState …Run Code Online (Sandbox Code Playgroud) 我在 Angular 2 中遇到问题,我知道这是一个反复出现的问题,但我找不到解决方案。我创建了一个从另一个组件调用的服务,没有问题。
问题出在服务中,我正在尝试进行 http POST 并获取错误:
[异常:TypeError:“caller”、“callee”和“arguments”属性可能无法在严格模式函数或 Function.remoteFunction 调用的参数对象上访问**
显然,错误是在handleErrorObservable中给出的,因为post也没有执行,查看Chrome中的网络选项卡,我没有看到任何对API的POST调用。
这是我的服务代码。
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions } from '@angular/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { User } from "./user";
import { HttpHeaders } from '@angular/common/http';
import { Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class RegisterService {
usersUrl: 'http://localhost:8080/TrabajoPromocion/users/';
constructor(private http:Http) { }
addBookWithObservable( ): Observable<User> {
let body …Run Code Online (Sandbox Code Playgroud)