我在理解如何在 angular2 中正确扩展服务时遇到了一些问题,可能是因为我不太了解如何在打字稿中扩展类。
@Injectable()
export class CallService{
constructor(private errror:string){
this.errMsg=errror;
}
private _errMsg:string;
set errMsg(arg0:string){
this._errMsg=arg0;
}
get errMsg():string{
return this._errMsg;
}
}
Run Code Online (Sandbox Code Playgroud)
@Injectable()
export class DownloadService extends CallService{
constructor(private error:string,private http:Http){
super(error)
}
}
Run Code Online (Sandbox Code Playgroud)
@Component({
selector:'my-app',
templateUrl:'app/app.component.html',
styleUrls:['app/app.component.css'],
directives:[ROUTER_DIRECTIVES,WaitComponent],
providers:[DownloadService,SwitcherService,CallService,WaitService]
})
export class AppComponent{
title:'App'
constructor(
private areadownloadservice:AreaDownloadService,
private waitService:WaitService,
private switcherservice:SwitcherService,
private callService:CallService){}
)
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是使用 CallService 扩展一些类,以便所有进行调用的类都有一个 errMsg 字符串属性来设置或获取,但我得到了这个异常:
没有 String 的提供者!
我错过了什么?
我正在尝试将数据发布到Angular的后端Node js文件中.表单提交后,函数调用:
cmdSubmit() : void
{
console.log(this.cli);
this.Cliservice.postdata(this.cli)
.then(clidata => this.clidata.push(clidata),
error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)
postdata功能代码:
postdata(obj: any): Promise<any> {
alert('hello');
let body = JSON.stringify({ obj });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.runUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
/*return this.http.post(this.runUrl, body, options)
.map(this.extractData)
.catch(res => {
// do something
// To throw another error, use Observable.throw
return Observable.throw(res.json());
});*/
}
private extractData(res: Response) {
let …Run Code Online (Sandbox Code Playgroud) 如果我想在整个应用程序中使用服务,我应该将其声明为提供者app.module.ts,但如果声明它也可以app.component.ts.
这两种方法有什么显着差异吗?
我在 CORS 场景下访问响应标头时遇到问题。我正在拨打 CORS 电话。因此,我在 API Manager 中配置了 API 配置以接受 CORS 请求(即为我的 REST 端点启用了 CORS)。
但是当我的应用程序(Angular2 应用程序)执行发布请求时,它(http.post)看不到响应标头。我在 Chrome Devtools 中检查了浏览器从远程服务器接收到的内容,结果发现浏览器中收到了所有预期的响应标头。显然,Angular 没有将其传递给我的代码,我无法访问标头。Gunter,建议我检查 CORS 标头
访问控制公开标头
我的问题: 当启用 CORS 时,我可以在哪里告诉 WSO2 API Manager 传递 pass 或设置此标头?我在 api-manager.xml 中尝试过,但重新启动后没有看到预期的标头(在我的例子中为标头“位置”)。
在有人将其标记为重复之前以下是我尝试过但失败的链接
场景我想将数据从我的 ng2 服务发送到组件,并且正在使用 ng2 HTTP 从 API 加载数据
下面是虚拟代码
我的服务
@Output() event_callback: EventEmitter<any> = new EventEmitter();
getUserDetails(id)
{
var user_data;
this.loadRemoteUrl('getUserdata?user_id=' + id).subscribe(
data => { user_data = data},
err => console.error(err),
() => {
console.log('Inside My Service');
this.user_data = user_data;
this.event_callback.emit(this.user_data);
}
);
}
Run Code Online (Sandbox Code Playgroud)
我的组件
constructor(private http:Http, private myService: MyService)
{
var userDetails;
myService.event_callback.subscribe(
data => this.callbackFunction()
);
}
callbackFunction()
{
console.log("Inside MyComponent")
}
Run Code Online (Sandbox Code Playgroud)
控制台日志
Inside My Service
Run Code Online (Sandbox Code Playgroud)
HTTP 请求正确返回数据,我在发出之前尝试转储,它工作但问题是我无法访问组件中的数据,我尝试传递数据,现在我只是一些记录消息来识别流,但仍然无法看到来自我的组件文件的日志消息。
我错过了什么?
我有一个有角度的2服务
import * as localforage from "localforage";
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class CommentService {
private localForage = require("localforage");
addComment (myvalue: string): Observable<Comment[]> {
var reply:ReplaySubject<any> = new ReplaySubject(1);
localforage.setItem(that.key, that.elencoCommenti).then(function (value) {
//throw new Error("Value cannot be 3");
reply.throw(Error('Error2'));
// reply.next( value );
// reply.complete();
});
return reply;
}
}
Run Code Online (Sandbox Code Playgroud)
该服务结合了提出异常的方法.当我尝试订阅
submitComment(){
// Variable to hold a reference of addComment
let commentOperation:Observable<string>;
commentOperation = this.commentService.addComment(this.model)
// Subscribe to observable
commentOperation.subscribe(
comments => {
console.log('ok:');
console.log(comments);
}, …Run Code Online (Sandbox Code Playgroud) 我正在使用 .share() 在服务的所有订阅者之间共享 Observable:
@Injectable()
export class ChannelsService {
private store: IChannel[] = [];
private _own: BehaviorSubject<IChannel[]> = new BehaviorSubject([]);
readonly own: Observable<IChannel[]> = this._own.asObservable().share();
...(the rest of the service basically makes CRUD http request and then calls this._own.next(result) to emit the result to all subscribers)
}
Run Code Online (Sandbox Code Playgroud)
问题:只有 Observable 的第一个订阅 (ChannelsService.own.subscribe(...)) 正在获取初始数据,其余订阅将“null”作为第一个订阅的值。接下来调用 this._own.next(result) 将正确地将其值发送给所有订阅者。
知道如何在多个订阅者之间 .share() 一个 Observable 并获取为所有订阅者发出的最后一个值吗?(我已经尝试过 .share().last() 但没办法...)。
谢谢!
我在实施NgZones方面遇到了麻烦.即使我已经定义了NgZone,我也会收到此错误."NodeInvocationException:由于错误导致预渲染失败:ReferenceError:未定义NgZone"
这是我的app.error-handle.ts文件,我使用的是NgZone.
import { ToastyService } from 'ng2-toasty';
import { ErrorHandler, Inject, NgZone } from '@angular/core';
export class AppErrorHandler implements ErrorHandler {
constructor(
private ngZone: NgZone,
@Inject(ToastyService) private toastyService: ToastyService) {
}
handleError(error: any): void {
this.ngZone.run(() => {
this.toastyService.error({
title: 'Error',
msg: 'An unexpected error happened.',
theme: 'bootstrap',
showClose: true,
timeout: 5000
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的webpack.config.vendor.js文件.
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'@angular/animations',
'@angular/common', …Run Code Online (Sandbox Code Playgroud) typescript visual-studio-code angular2-services angular2-zone asp.net-core-2.0
我正在做一个angular2项目,在assets文件夹中有一个文件,并且创建了一个在运行应用程序时下载文件的按钮。
我看到上述问题有很多解决方案,所以我很困惑。你能帮忙吗?
<button pButton type="button" (click)="f1()" label="Download Sample Defaults
XML File"></button>
Run Code Online (Sandbox Code Playgroud)
我需要f1()的代码,当单击上面的按钮时,该代码可以帮助我将文件下载到我的“下载”文件夹中。帮助表示赞赏。谢谢
我想实现自动完成功能,所以我发现一个相同的选项是使用多选下拉菜单。所以我使用了这个模块 -
https://www.npmjs.com/package/ng-multiselect-dropdown
但是在同样实施之后,我收到了这些错误 -
错误 -
ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'placeholder' since it isn't a known property of 'ng-
multiselect-dropdown'.
1. If 'placeholder' is an Angular directive, then add 'CommonModule'
to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the
'@NgModule.schemas' of this component. ("
<ng-multiselect-dropdown
[ERROR ->][placeholder]="'custom placeholder'"
[data]="dropdownList"
[(ngModel)]="selectedItems"
"): ng:///AdminLayoutModule/HierarchySearchComponent.html@7:0
Run Code Online (Sandbox Code Playgroud)
当我在我的 component.html 中评论占位符时,我收到此错误 -
Can't bind to 'data' since it isn't a known …Run Code Online (Sandbox Code Playgroud)