我创建了简单的WebSocket服务和组件,当通过WebSocket接收新数据时,我很难更新视图.
websocket.service.ts
import {Injectable} from "angular2/core";
import {Observable} from 'rxjs/Observable';
@Injectable()
export class WebsocketService {
observable: Observable;
websocket = new WebSocket('ws://angular.local:8080');
constructor() {
this.observable = Observable.create(observer =>
this.websocket.onmessage = (msg) => observer.next(msg);
this.websocket.onopen = (msg) => console.log('openned');
);
}
}
Run Code Online (Sandbox Code Playgroud)
runner.component.ts
import {Component} from "angular2/core";
import {WebsocketService} from "./websocket.service";
@Component({
selector: "runners-list",
templateUrl: "../partials/runners-list.html",
providers: [WebsocketService],
styleUrls: ["../css/app.css"]
})
export class RunnerComponent {
output: any;
constructor(private _websocketService: WebsocketService) {
_websocketService.observable.subscribe(
function onNext(data) {
this.output = data;
console.log(this.output);
},
function onError(error) …Run Code Online (Sandbox Code Playgroud) 所以我知道你可以让两个不相关的组件通过服务相互通信,让一个组件在服务中发出一个事件,另一个组件在服务中订阅它.
我的问题:
服务可以直接调用组件中的函数吗?
首先,我知道这个答案之前已经发布了很多次,但我不能让我的工作成功,也许这里有人可以提供帮助.
我正在使用angular-cli beta 5来生成一个新项目.我使用角度2 rc1.
我有一个名为ApplicationConfiguration的类< - 这个我想创建一个实例,通过我的应用程序的每个组件.
在我的主要内容中,我有:
bootstrap(MyProjWebAppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS, ApplicationConfiguration, provide(Http, {
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, appConfig: ApplicationConfiguration) => new HttpServiceLayer(xhrBackend, requestOptions, router, appConfig),
deps: [XHRBackend, RequestOptions, Router, ApplicationConfiguration]
})]);
Run Code Online (Sandbox Code Playgroud)
我的ApplicationConfiguration类:
@Injectable()
export class ApplicationConfiguration {
constructor() {
console.log('aaa');
}
}
Run Code Online (Sandbox Code Playgroud)
以及我如何注入ApplicationConfiguration的示例组件:
import { ApplicationConfiguration } from '../..//services/application-configuration/application-configuration';
@Component({
moduleId: module.id,
selector: 'app-log-in',
templateUrl: 'log-in.component.html',
styleUrls: ['log-in.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [ApplicationConfiguration, LogInService]
})
export class LogInComponent implements OnInit {
constructor(private _service: LogInService, private appConfig: …Run Code Online (Sandbox Code Playgroud) 所以我有一个组件和服务....服务进行API调用并填充组件的变量(this.data)
在组件方面一切运作良好,战略位置上的console.log总是返回价值......这很简单
当我想在视图中显示数据时(我只想说{{data.name}},我得到一个错误...无法读取未定义的属性'name'
这个错误实际上是在我放入我的服务调用的console.logs之前打印出来的....所以我认为它不会等待回来的电话......
import { Component, OnInit } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { Index, IndexColumn } from '../index';
import { IndexService } from '../index.service';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'ex'})
export class StringifyPipe implements PipeTransform {
transform(value: any): string {
return JSON.stringify(value);
}
}
@Component({
moduleId: module.id,
selector: 'app-index',
template: require('./indicesDetails.component.html'),
styleUrls: [String(require('./indicesDetails.component.less'))],
providers: [IndexService],
pipes: [StringifyPipe]
})
export class IndicesDetailsComponent implements OnInit {
errorMessage: string;
index: Index;
mode = …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Angular 2中创建一个通用数据服务,我遇到了一个奇怪的错误.本质上,我正在创建一个HTTP服务,其方法包含api url的一部分,以便我可以将它用于多种情况.例如,我想传递'projects /'并加入'api /'来获取'api/projects /'然后我可以在http调用中使用它.
我目前的dataService.ts:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';
import { Configuration } from '../app.constants';
@Injectable()
export class DataService {
private actionUrl: string;
private headers: Headers;
constructor(private _http: Http, private _configuration: Configuration, public action: string) {
this.actionUrl = _configuration.ApiUrl
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
public GetAll (action: string): Observable<any> {
return this._http.get(this.actionUrl + action).map((response: Response) => …Run Code Online (Sandbox Code Playgroud) 我必须在这里做错事,但我不知道是什么......我是一个Angular2新手在我的第一个ng2应用程序中磕磕绊绊.
我正在尝试从组件内访问服务上的方法,但该服务仅在构造函数()和ngOnInit()中定义,它在我的其他组件函数中返回为未定义.
这与此问题类似,但我使用的是private关键字,但仍然存在问题.
这是我的服务:
import { Injectable } from "@angular/core";
import { AngularFire,FirebaseListObservable } from 'angularfire2';
import { User } from './user.model';
@Injectable()
export class UserService {
userList$: FirebaseListObservable<any>;
apples: String = 'Oranges';
constructor(private af: AngularFire) {
this.initialize();
}
private initialize():void {
this.userList$ = this.af.database.list('/users');
}
getTest(input:String):String {
return "Test " + input;
}
getUser(userId:String):any {
//console.log('get user',userId);
let path = '/users/'+userId;
return this.af.database.object(path);
}
}
Run Code Online (Sandbox Code Playgroud)
我的组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } …Run Code Online (Sandbox Code Playgroud) 如何使用带有http和observables的angular2在json文件中添加/更新/删除产品/项目.以下是我的代码,GET Products工作正常.请告知其他人
产品list.component
export class ProductListComponent implements OnInit {
pageTitle: string = 'Product List';
imageWidth: number = 50;
imageMargin: number = 2;
showImage: boolean = false;
listFilter: string;
errorMessage: string;
products: IProduct[];
constructor(private _productService: ProductService) {
}
toggleImage(): void {
this.showImage = !this.showImage;
}
deleteItem() : void {
this._productService.deleteProduct();
}
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)
product.service.ts
export class ProductService {
private _productUrl = 'api/products/products.json';
private headers = new Headers({'Content-Type': 'application/json'}); …Run Code Online (Sandbox Code Playgroud) 注意:我不需要一个解决方案来迭代HTML模板中的json数据.我可以通过*ngFor来做.我想在component.ts中实现它,我实际上得到了响应.
我在propload.service.ts中有一个服务,它提供了属性文件中的键和值对列表.
`getData(): Observable<Object[]> {
return this.http.get(this.dummyDataUrl)
.map((response:Response)=>response.json())
.catch(this.handleError);
}`
Run Code Online (Sandbox Code Playgroud)
我在demo.component.ts文件中调用此服务,如下所示
`ngOnInit():void
{
this.dummyService.getData().subscribe(response=> {
console.log(response)
});
}`
Run Code Online (Sandbox Code Playgroud)
在这里,我能够在控制台中记录完整的json响应对象,我可以使用chrome中的开发人员选项查看.如果我展开该对象,那么我将获得来自属性文件的键值对.直到这么多,它工作正常.
我无法从第二个代码片段中的响应对象访问键值对,就在console.log()的正下方,我希望能够有一些for循环或其他一些方式让我可以单独获取键值对.
最终任务是能够将这些数据存储在浏览器的会话存储中.我已经有了这样做的方法,但为此我需要单独的键和值对,以便能够在两者之间执行一些修改,然后在会话存储中记录相同的内容.
我尝试了一些内置的方法,比如response.keys,它应该返回所有键的列表,但是如果我尝试记录它仍然在控制台中,我每次都会得到未定义的.
任何人都可以建议我如何得到结果?
同样非常感谢.
我正在使用Angular 2+.
作为组件的ngOnDestroy的一部分,我想销毁/删除服务实例.
这可能吗?
谁知道怎么样?
当然,下次加载组件时,我想重新创建服务,然后在组件死亡时销毁.
编辑:
我想要实现的是每个组件的专用Web套接字.当组件被销毁(ngOnDestroy)时,断开websocket.
我将许多HTTP请求发送到服务器,并且服务器返回每个请求带有新访问令牌的响应(可能在标题或正文中).
有没有办法在它完成之前或之后处理所有响应,比如某些后端框架中的请求的中间件?