一种是通过事件,另一种是通过调用方法。我试图在我的应用程序中实现聚合模式。
我有AuthService,在这里我处理auth结果并发出事件。
if (auth) { this.eAuth.emit(true) } else { this.eAuth.emit(false) }
Run Code Online (Sandbox Code Playgroud)
我可以订阅AuthComponent
_authService.eAuth.subscribe( (isAuth) => this.handleAuthResult(isAuth) )
Run Code Online (Sandbox Code Playgroud)
而且效果很好。但是AggregateService也需要了解这一点,并将此信息广播到UserService,LoadDataService等。
怎么做?
upd:我的AggregateService没有组件,我已经向其中注入AuthService。
我正在尝试实现我在Stack Overflow中找到的解决方案,但面临困难.我有一个服务和一个组件,并且在实现上有些不正确.
错误:TypeError:无法读取undefined属性'next'可能有什么错误或缺失?有什么更多的缺失?同样在我的终端窗口,我收到此错误,但它没有反映在我的浏览器控制台上:错误TS1005:'=>'预期.
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
@Injectable()
export class GlobalService {
data: any;
dataChange: Observable<any>;
constructor() {
this.dataChange = new Observable((observer:Observer) { // this is the TS1005 error.
this.dataChangeObserver = observer;
});
}
setData(data:any) {
this.data = data;
this.dataChangeObserver.next(this.data); //Line of the critical error (next)
}
}
Run Code Online (Sandbox Code Playgroud)
这是消耗服务的组件....(我只会放置相关的行)
import {GlobalService} from "../../../global.service";
import(...)
@Component({
providers: [GlobalService],
template: `<p>{{myData}}<>/p><span (click)="addTag(1, 'test')">Add more</span>`
});
export class MyComponent {
addTag (id,desc){
this._global.setData({ attr: 'some …Run Code Online (Sandbox Code Playgroud) 我读了一篇关于如何将Http服务注入Angular2应用程序的文章.
https://angular.io/docs/ts/latest/api/http/HTTP_PROVIDERS-let.html
import {HTTP_PROVIDERS, Http} from 'angular2/http';
@Component({
selector: 'app',
providers: [HTTP_PROVIDERS],
....
Run Code Online (Sandbox Code Playgroud)
我认为Http服务已经包含在HTTP_PROVIDERS中.(如下文所述,根据文件).
"The providers included in HTTP_PROVIDERS include:
Http
XHRBackend
BrowserXHR - Private factory to create XMLHttpRequest instances
RequestOptions - Bound to BaseRequestOptions class
ResponseOptions - Bound to BaseResponseOptions class"
Run Code Online (Sandbox Code Playgroud)
如果是这样的话,为什么我们仍然需要导入Http?我们能做到吗
import {HTTP_PROVIDERS} from 'angular2/http';
Run Code Online (Sandbox Code Playgroud)
另一方面,更具体地说,我们可以将组件提供商更改为
providers: [Http]吗?或者在引导程序中,我们可以bootstrap(app, [Http])吗?
我正在使用Angular 2.0.0-beta.16并尝试从我的RESTful API获取数据.我有以下服务:
import {Injectable} from 'angular2/core';
import {Jsonp, Response, Headers, RequestOptions} from 'angular2/http';
import {Store} from './store';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class StoreService {
constructor(private jsonp: Jsonp) {
}
getStores(): Observable<Store[]> {
console.log("getting stores");
// let headers = new Headers({ 'Content-Type': 'application/json' });
// let options = new RequestOptions({ headers: headers });
return this.jsonp.get("http://localhost:8080/stores")
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
console.log(res.status);
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad …Run Code Online (Sandbox Code Playgroud) Angular2可以通过http方法删除发送json正文吗?
我试了,它说错了
ORIGINAL EXCEPTION: options.search.clone is not a function
Run Code Online (Sandbox Code Playgroud)
service.ts
deletetag(tagid: number): Observable<any> {
let body = JSON.stringify(
{
"token": "test",
"content": {
"tagId": tagid
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.delete("http://localhost:8080/backend/tag", body, options)
.map(res => this.extractData(res))
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
component.ts
this.tagService.deletetag(1)
.subscribe(
data => { },
error => { },
() => { }
);
Run Code Online (Sandbox Code Playgroud) 我想要的以后做什么Observable/ subscribe完成.我正在改变方法中的Input属性subscribe( onNext ),但从ngOnChanges不触发.
我应该做些什么呢?
import { Component, EventEmitter,
OnInit, AfterViewInit, OnChanges, SimpleChanges,
Input, Output
} from '@angular/core';
@Component({
templateUrl: 'myTemplate.html'
, providers: [ NamesService ]
})
export class MyPage {
@Input() names: any[];
constructor( public namesSvc: NamesService) {}
ngOnInit() {
this.getNames$()
}
getNames$() : void {
this.nameService.get().subscribe(
(result)=>{
this.names = result;
console.log(`getNames$, names=${this.names}`);
// I could doSomething() here, but it doesn't seem like the correct place
// doSomething()
}
, …Run Code Online (Sandbox Code Playgroud) 我的html调用此组件
<navbar [title]="'Recorridos'"
[hasNavbarItems]="true"
[itemsJsonFileName]="'recorrido-list-navbar-items.json'"
(btnActionClicked)="onBtnActionClicked($event)"
(btnFilterClicked)="onBtnFilterClicked($event)">
</navbar>
Run Code Online (Sandbox Code Playgroud)
这是一个动态组件,然后在onBtnActionClicked($ event)需要重定向
<a [routerLink]="['/parent/detail', detail.detailId]">{{detail.detailId}}</a>
Run Code Online (Sandbox Code Playgroud)
但正如你所看到的那样无法从html中添加,那么在我的组件中我可以调用按钮单击执行
onBtnActionClickedV(event) {
}
Run Code Online (Sandbox Code Playgroud)
在该函数中,我如何像routerLink一样重定向?
angularjs-directive angular2-routing angular2-services angular
我的Angular2代码已经从我在网上看过的各种教程拼凑而成webservices.services.ts
import { Component, OnInit, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import {HttpModule} from '@angular/http';
import {JsonpModule} from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class WebService {
constructor(private http: Http, private router: Router,private _jsonp: JsonpModule) { }
public getDataFromBackend() {//
return this.http.get('http://localhost:5000/getstuff')
.map(data=>{
data.json();
console.log(data.json());
return data.json();
})
}
}
Run Code Online (Sandbox Code Playgroud)
App.Component.ts
import { Component , OnInit} from '@angular/core';
import { …Run Code Online (Sandbox Code Playgroud) 我有一个文件data.json,我想在我的angular 2应用程序中导入.我正在获取带有HTML输入标签的文件.
<input type="file" (change)="onImport($event)"/>
Run Code Online (Sandbox Code Playgroud)
在我的typescript文件中,我想读取这个data.json文件,并将文件内容存储在JSON数组中.我已经搜索但找不到任何方法来阅读文件或任何可以帮助我的库.
我是Angular2的新手,在这里我试图循环遍历数组"mmEditorTypes"并检查条件,如果条件满足,那么我将执行"open方法".
但每当我执行以下代码时,我收到此错误:
portalModeService:portalMode的加载抛出异常:
TypeError:无法读取未定义的属性'forEach'.
有人能让我知道如何解决这个错误吗?
porta.service.ts:
function isAppContained(viewState, appType){
let angular:any;
let isContained = false;
angular.forEach(viewState.appViewStates, function (appViewState) {
if (appViewState.signature.appType === appType) {
isContained = true;
}
});
return isContained;
}
Run Code Online (Sandbox Code Playgroud)