我有多个组件(在 NgFor 循环中)调用相同的服务。
我想要的是,当一个组件更改同一服务中的值时,该新值会被发送到调用该服务的每个组件,并随后更新组件变量中的该值。
我希望这是有道理的。
如果您需要更多信息,请告诉我。
我正在尝试编写一个Angular服务,似乎有些东西丢失了.我的问题是它没有向Angular控制器返回任何值
getPrepTimes() 方法不返回http数据
但是当我检查网络时(通过Chrome开发工具),它将正确调用外部api并返回一个json对象作为响应
#my service
'use strict';
angular.module('recipeapp')
.service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes();
function getPrepTimes(){
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function (data, status, header, config){
return data;
});
};
}
]);
#controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime;
}]);
Run Code Online (Sandbox Code Playgroud)
当我getPrepTimes()通过返回字符串检查方法时,它可以工作.这里可能缺少什么?
这是我的工厂:
.factory('userService',()){
var user = {};
return {
getFirstname : function () {
return user.firstname;
},
setFirstname : function (firstname) {
user.firstname = firstname;
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的两个控制器MainCtrl和AccountEditCtrl中使用此服务我在我的MainCtrl中使用我的getFirstname()和在AccountEditCtrl中使用setFirstname
.controller('MainCtrl',['userService', function(userService){
$scope.userName = userService.getFirstName();
}]);
.controller('AccountEditCtrl',['userService', function(userService){
userService.setFirstname("New First Name");
}]);
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我使用userService.setFirstname()时,$ scope.userName不会在MainCtrl中更改.
我已经谷歌了很多这个问题,但没有找到任何相关的文章或stackoverflow问题虽然有很多问题具有相同的标题但在场景中有所不同.我无法在服务的构造函数上要求依赖项,这就是我收到此错误的原因.
Bootstrap at least one component before injecting Router. ; Zone: <root> ; Task: Promise.then ; Value: Error: Bootstrap at least one component before
Run Code Online (Sandbox Code Playgroud)
注意:如果我只是clear the constructor在其中定义的依赖关系,CustomerService class它就像一个魅力.
@Injectable()
export class CustomerService
constructor(private authService: AuthService, private siteService: SiteService) { }
Run Code Online (Sandbox Code Playgroud)
AuthService和站点服务类及其依赖项加载没有问题.只是AuthService和SiteService类的一些sudo外观
@Injectable()
export class AuthService
constructor(private http: Http, private storageService: StorageService,
private siteService: SiteService, private router: Router) {}
@Injectable()
export class SiteService {
constructor(private http: Http, private storageService: StorageService) {}
Run Code Online (Sandbox Code Playgroud)
还有App Module @ngModule装饰. …
我已经构建了一个共享数据服务,旨在保存用户登录详细信息,然后可以使用它来显示标题上的用户名,但我无法使其工作.
这是我的(缩写)代码:
// Shared Service
@Injectable()
export class SharedDataService {
// Observable string source
private dataSource = new Subject<any>();
// Observable string stream
data$ = this.dataSource.asObservable();
// Service message commands
insertData(data: Object) {
this.dataSource.next(data)
}
}
Run Code Online (Sandbox Code Playgroud)
...
// Login component
import { SharedDataService } from 'shared-data.service';
@Component({
providers: [SharedDataService]
})
export class loginComponent {
constructor(private sharedData: SharedDataService) {}
onLoginSubmit() {
// Login stuff
this.authService.login(loginInfo).subscribe(data => {
this.sharedData.insertData({'name':'TEST'});
}
}
}
Run Code Online (Sandbox Code Playgroud)
...
// Header component
import { SharedDataService } from 'shared-data.service'; …Run Code Online (Sandbox Code Playgroud) 我有一个带有observable的服务,通过组件订阅.当订户显示初始值时,这似乎有效.我有另一个组件,然后更新observable但是新值不会显示.
服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
@Injectable()
export class BannerService {
banners$: Observable<any[]> = Observable.of([]);
getBanners(): Observable<any[]> {
return this.banners$;
}
setBanners(banners: any[]): void {
this.banners$ = Observable.of(banners);
}
}
Run Code Online (Sandbox Code Playgroud)
订阅者组件:
import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { BannerService } from './../banner/banner.service';
@Component({
selector: '.banner',
templateUrl: './banner.component.html',
styleUrls: ['./banner.component.sass'],
encapsulation: ViewEncapsulation.None
})
export class BannerComponent implements OnInit {
constructor(private bannerService: BannerService){}
ngOnInit() {
this.bannerService.banners$.subscribe(banners => {
console.log(banners); …Run Code Online (Sandbox Code Playgroud) angular-services angular-components angular angular-observable
你好,我得到这样的错误是什么原因?
StaticInjectorError [Http]:StaticInjectorError [Http]:NullInjectorError:没有Http提供程序!在tryResolveToken(core.js:1153)的resolveToken(core.js:1211)的NullInjector.get(core.js:923)处在resolveToken(core.js :)的StaticInjector.get(core.js:1024)输入代码1211)在tryResolveToken(core.js:1153)在StaticInjector.get(core.js:1024)在resolveNgModuleDep(core.js:10585)在NgModuleRef.get(core.js:11806)在resolveDep(core.js:12302) )
import { Injectable } from '@angular/core' import {Todo} from './Todo'
import {Http, Response,Headers,RequestOptions} from '@angular/Http' import {Observable} from 'rxjs/Observable' import 'rxjs/add/operator/do' import 'rxjs/add/operator/catch' import 'rxjs/add/operator/map'
@Injectable() export class TodoService{
constructor(private http: Http){}
todoUrl = "https://jsonplaceholder.typicode.com/todos";
getTodos():Observable{ return this.http.get("https://jsonplaceholder.typicode.com/todos") .map((res:Response)=>res.json()) .do(data=>console.log("TODOS LIST")) } }
Run Code Online (Sandbox Code Playgroud) 我在使用Angular 5服务时面临以下问题,请您帮我解决下面的代码有什么问题
我已经解决了以下问题,但没有帮助我
我只想初始化类中的值并在方法中使用它
虽然我已经在类中定义的URL值我得到误差Cannot read property 'url' of undefined为线console.log(this.url);
@Injectable()
export class OwnService {
public accessTokenvalue = '';
public url = 'https://www.someurl.com/id=';
constructor(private hp: HelpService) {
}
public gethpPhotos() {
this.hp.login()
.then(function (response: LoginResponse) {
console.log(response);
console.log(this.url);
})
.catch((error: any) => console.error(error));
}
}
Run Code Online (Sandbox Code Playgroud) 如何动态添加组件?
toolbar.component.ts:
@Component({
selector: 'app-toolbar',
template: '<button>Add Text component</button>'
})
export class ToolbarComponent {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
section.component.ts:
@Component({
selector: 'div[app-type=section]',
template: ''
})
export class SectionComponent {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
text.component.ts:
@Component({
selector: 'app-text',
template: '<p>This is dynamically component</p>'
})
export class TextComponent {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
view.component.ts:
@Component({
selector: 'app-view',
template: `<div class="container">
<app-toolbar></app-toolbar>
<div app-type="section" id="SECTION1" class="active"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class SectionComponent {}
Run Code Online (Sandbox Code Playgroud)
当我点击ToolBarComponent时,我想将TextComponent添加到具有"active"类的SectionComponent.
我正在尝试在服务中设置数据,然后在服务中填充数据后导航,我有一个时间问题,页面在服务能够填充之前导航.
我在服务中有以下代码
addToken(token) {
this.cookieService.set( 'token', token );
}
Run Code Online (Sandbox Code Playgroud)
单击按钮时的以下代码: -
this.token.addToken(res);
this.router.navigate(['/admin']);
Run Code Online (Sandbox Code Playgroud)
触发路由器后,/ admin页面会触发带有以下标题的端点: -
authHttpHeaders = new HttpHeaders({
'Authorization': 'Bearer ' + this.token.getToken(),
'Content-Type' : 'application/json',
'Cache-Control': 'no-cache'
});
Run Code Online (Sandbox Code Playgroud)
getToken()函数只接收来自cookie的令牌: -
getToken() {
return this.cookieService.get('token');
}
Run Code Online (Sandbox Code Playgroud)
如何在触发路由器导航之前确保addToken()已完成.
我知道我可以通过setTimeout实现它,但我真的不喜欢这样做.
在导航路由器被触发之前,我宁愿有某种形式的可观察或看到令牌不等于null或空.
在此先感谢您的帮助.
angular-services ×10
angular ×8
angularjs ×3
javascript ×3
typescript ×3
angular5 ×2
angular-http ×1
angular6 ×1
components ×1
observable ×1
viewchild ×1